In [1]:
print 'hello world'
hello world
In [2]:
2+2
Out[2]:
4
In [3]:
#illustration of for loop and range
count =0
for i in range(10):
    if i != 0:
        print '+',
    else:
        print ' ',
    print i
    count += i
print "---\n",' '+str(count)
  0
+ 1
+ 2
+ 3
+ 4
+ 5
+ 6
+ 7
+ 8
+ 9
---
 45
In [4]:
#illustration of strings as lists
string = ''
alphabet='abcdefghijklmnopqrstuvwxyz'
for i in range(1,10):
    string += alphabet[-i]
    print len(string),string
1 z
2 zy
3 zyx
4 zyxw
5 zyxwv
6 zyxwvu
7 zyxwvut
8 zyxwvuts
9 zyxwvutsr
In [5]:
#illustration of lists and dict
list=[]
dict={}
string=''
for i in range(1,10):
        string += alphabet[-i]
        list.append(string)
        list += [string]
        dict[string] = i
print list,"\n",dict
['z', 'z', 'zy', 'zy', 'zyx', 'zyx', 'zyxw', 'zyxw', 'zyxwv', 'zyxwv', 'zyxwvu', 'zyxwvu', 'zyxwvut', 'zyxwvut', 'zyxwvuts', 'zyxwvuts', 'zyxwvutsr', 'zyxwvutsr'] 
{'zyxwvutsr': 9, 'zyxw': 4, 'zyxwvuts': 8, 'zyxwvu': 6, 'zyxwv': 5, 'zy': 2, 'zyxwvut': 7, 'z': 1, 'zyx': 3}
In [6]:
list[3]
Out[6]:
'zy'
In [7]:
dict['z']
Out[7]:
1
In [8]:
#dict values can be any object
dict['a']=['a1','a2','a3','a4']
dict['b'] = ['a'+str(j) for j in range(10)]
dict['c']={}
dict['c']['xyz']='alpha'
In [9]:
dict
Out[9]:
{'a': ['a1', 'a2', 'a3', 'a4'],
 'b': ['a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9'],
 'c': {'xyz': 'alpha'},
 'z': 1,
 'zy': 2,
 'zyx': 3,
 'zyxw': 4,
 'zyxwv': 5,
 'zyxwvu': 6,
 'zyxwvut': 7,
 'zyxwvuts': 8,
 'zyxwvutsr': 9}
In [10]:
#dicts can be sorted on keys
score={'Alice':90,'Bob':65,'Eve':95,'Charles':75}
for name in sorted(score.keys()):
    print name,score[name]
print '\n','average=',sum(score.values())/len(score)
Alice 90
Bob 65
Charles 75
Eve 95

average= 81
In [11]:
#or on values
for name in sorted(score.keys(),key=score.get,reverse=True):
    print name,score[name]
print '\n','average=',sum(score.values())/len(score)
Eve 95
Alice 90
Charles 75
Bob 65

average= 81
In [12]:
#http://matplotlib.org/examples/api/unicode_minus.html
plot(10*np.random.randn(100), 10*np.random.randn(100), 'o')
title('Some Random Data')
Out[12]:
<matplotlib.text.Text at 0x10976f6d0>
In [13]:
data=(1,3,8,6,4,2)
plot(range(len(data)),data,label="first")
moredata = -array(data)
plot(range(len(moredata)),moredata,label="second")
grid(True)
xlabel('time')
ylabel('Gb used')
legend()
Out[13]:
<matplotlib.legend.Legend at 0x102d92990>
In [14]:
#http://matplotlib.org/examples/pylab_examples/histogram_demo.html
mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)

# the histogram of the data
n, bins, patches = hist(x, 50, normed=1, facecolor='green', alpha=0.75)

# add a 'best fit' line
y = mlab.normpdf( bins, mu, sigma)
l = plot(bins, y, 'r--', linewidth=1)

xlabel('Smarts')
ylabel('Probability')
title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$')
axis([40, 160, 0, 0.03])
grid(True)
#savefig("kln.png", dpi=72)
In [ ]: