checking python version $ python --version

In [ ]:
print 'Hello World'

In [ ]:
print ('Hello World')

In [ ]:
print("Hello World")

In [ ]:
import keyword

In [ ]:
print (keyword.kwlist)

In [ ]:
len(keyword.kwlist)

In [ ]:
a, b, _, _ = 1, 'potter', 23, 43

In [ ]:
a, b

In [ ]:
x, _, y, _ = 1, 2, 3, 4

In [ ]:
x, y

In [ ]:
a = b = c =2.17

In [ ]:
a,b,c

In [ ]:
# to get input from the user
user_input = raw_input("Give me some input!: ")

In [ ]:

Numpy

A numpy array is a grid of values, all of the same type and is is indexed by a tuple of non-negative integers.

The number of dimensions is the RANK of the array.

The SHAPE of the array is a tuple of integers giving the size of the array along each dimension.


In [3]:
import numpy as np

In [21]:
a = np.array([1,2,3])  # creates RANK 1 array

In [22]:
a


Out[22]:
array([1, 2, 3])

In [23]:
print(type(a))


<type 'numpy.ndarray'>

In [24]:
print(a.shape)


(3,)

In [25]:
print(a)


[1 2 3]

In [26]:
print(a[0], a[1], a[2])


(1, 2, 3)

In [27]:
a[0]


Out[27]:
1

In [28]:
a[1] = 123445

In [29]:
a


Out[29]:
array([     1, 123445,      3])

In [15]:
print(a)


[     1 123445      3]

In [30]:
a[1] = 15

In [31]:
print(a)


[ 1 15  3]

In [32]:
b = np.array([[1, 2, 3], [4, 5, 6]])

In [33]:
print(b.shape)


(2, 3)

In [34]:
print(b[0, 0])


1

In [36]:
print(b[1,2])


6

In [39]:
m_npZEROS = np.zeros((2,2))

In [42]:
m_npZEROS


Out[42]:
array([[ 0.,  0.],
       [ 0.,  0.]])

In [40]:
m_npONES = np.ones((3,3))

In [41]:
m_npONES


Out[41]:
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])

In [54]:
m_npFULL = np.full((4,5), 17, dtype='int64')

In [55]:
m_npFULL


Out[55]:
array([[17, 17, 17, 17, 17],
       [17, 17, 17, 17, 17],
       [17, 17, 17, 17, 17],
       [17, 17, 17, 17, 17]])

In [60]:
m_npEYE = np.eye(3, 4)

In [61]:
m_npEYE


Out[61]:
array([[ 1.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.]])

In [62]:
m_npEYE = np.eye(3, 4, 1)

In [63]:
m_npEYE


Out[63]:
array([[ 0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  1.]])

In [64]:
m_npEYE = np.eye(3, 4, -1)

In [65]:
m_npEYE


Out[65]:
array([[ 0.,  0.,  0.,  0.],
       [ 1.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.]])

In [74]:
m_npRANDOM = np.random.random((2,2))
m_npRANDOM


Out[74]:
array([[ 0.77683136,  0.96197286],
       [ 0.23386338,  0.54167597]])

In [ ]:


In [75]:
m_npRANDOM = np.random.random((2,2))
m_npRANDOM


Out[75]:
array([[ 0.07241208,  0.8651905 ],
       [ 0.64797112,  0.66805613]])

In [76]:
a = np.array([[1,2,3], [4,5,6], [7,8,9]])

In [78]:
b = a[:2, 1:3]
print(b)


[[2 3]
 [5 6]]

A slice of the array is a view into the same data, so modifying the slice will also modify the original array


In [79]:
print(a[1,1])


5

In [81]:
print(b[1, 0])
b[1,0] = 100
print(b[1,0])
print(a[1,1])


5
100
100

In [82]:
a


Out[82]:
array([[  1,   2,   3],
       [  4, 100,   6],
       [  7,   8,   9]])

In [83]:
row_r1 = a[1, :]
row_r2 = a[1:2, :]
print(row_r1, row_r1.shape)
print(row_r2, row_r2.shape)


(array([  4, 100,   6]), (3,))
(array([[  4, 100,   6]]), (1, 3))

In [87]:
(np.eye(4)).shape


Out[87]:
(4, 4)

In [88]:
a = [[1,2,3], [4,5,6]]

In [89]:
print(a)


[[1, 2, 3], [4, 5, 6]]

In [96]:
b = a[1]

In [97]:
b


Out[97]:
[4, 5, 6]

In [98]:
b = a[:]

In [99]:
b


Out[99]:
[[1, 2, 3], [4, 5, 6]]

In [100]:
b = [[10,20,30], [40,50,60]]

In [101]:
a


Out[101]:
[[1, 2, 3], [4, 5, 6]]

In [102]:
b


Out[102]:
[[10, 20, 30], [40, 50, 60]]

In [104]:
a = np.array([[1,2],[3,4],[5,6]])
print(a)


[[1 2]
 [3 4]
 [5 6]]

In [109]:
# integer array indexing
x = a[[0,1,2], [0,1,0]]
print(x)
print(x.shape)


[1 4 5]
(3,)

In [112]:
# slicing
y = np.array([a[0,0], a[1,1], a[2,0]])
print(y)
print(y.shape)


[1 4 5]
(3,)

In [113]:
# selcting/mutating one element from each row of a matrix

In [114]:
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10,11,12]])

In [117]:
print(a)
print(a.shape)


[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
(4, 3)

In [118]:
b = np.array([1,2,0,1])

In [119]:
b


Out[119]:
array([1, 2, 0, 1])

In [120]:
print(a[np.arange(0,4), b])


[ 2  6  7 11]

In [121]:
print(a[np.arange(0,4), b])


[ 2  6  7 11]

In [125]:
a[np.arange(0,4),b] +=100

In [126]:
a


Out[126]:
array([[  1, 102,   3],
       [  4,   5, 106],
       [107,   8,   9],
       [ 10, 111,  12]])

Boolean array indexing lets us pick out arbitrary elements of an array.

This type of indexing is used to slect the elements of an array that satisfy some condition.


In [127]:
a = np.array([[1,2],[3,4],[5,6]])

In [128]:
bool_idx = (a>2)

In [129]:
bool_idx


Out[129]:
array([[False, False],
       [ True,  True],
       [ True,  True]], dtype=bool)

In [132]:
#boolean indexing: It produces a Rank 1 array

print(a[bool_idx])


[3 4 5 6]

In [133]:
print(a[a>3])


[4 5 6]

In [162]:
m_list = [1,2,3]
m_npARRAY = np.array([1,2,3])

In [163]:
for e in m_list:
    print e


1
2
3

In [164]:
for e in m_npARRAY:
    print e


1
2
3

In [165]:
m_list.append(4)

In [166]:
m_list


Out[166]:
[1, 2, 3, 4]

In [167]:
m_npARRAY.append(4)


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-167-edebec8cb83e> in <module>()
----> 1 m_npARRAY.append(4)

AttributeError: 'numpy.ndarray' object has no attribute 'append'

In [168]:
m_list += [5]
m_list


Out[168]:
[1, 2, 3, 4, 5]

In [169]:
m_npARRAY += [5]
m_npARRAY


Out[169]:
array([6, 7, 8])

In [170]:
m_list += [6,7]
m_list


Out[170]:
[1, 2, 3, 4, 5, 6, 7]

In [171]:
m_npARRAY += [6,7]


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-171-fbd76a1f26d1> in <module>()
----> 1 m_npARRAY += [6,7]

ValueError: operands could not be broadcast together with shapes (3,) (2,) (3,) 

In [172]:
m_npARRAY + m_npARRAY


Out[172]:
array([12, 14, 16])

In [175]:
print m_npARRAY
print m_npARRAY * 2


[6 7 8]
[12 14 16]

In [176]:
print(m_list)
print(m_list * 2)


[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7]

In [179]:
print(m_npARRAY)
print(m_npARRAY ** 2)


[6 7 8]
[36 49 64]

In [180]:
print(m_npARRAY)
print(np.sqrt(m_npARRAY))


[6 7 8]
[ 2.44948974  2.64575131  2.82842712]

In [181]:
print(m_list)
print(np.sqrt(m_list))


[1, 2, 3, 4, 5, 6, 7]
[ 1.          1.41421356  1.73205081  2.          2.23606798  2.44948974
  2.64575131]

In [183]:
print(m_npARRAY)
print(np.log(m_npARRAY))


[6 7 8]
[ 1.79175947  1.94591015  2.07944154]

In [184]:
print(m_npARRAY)
print(np.exp(m_npARRAY))


[6 7 8]
[  403.42879349  1096.63315843  2980.95798704]

In [185]:
a = np.array([1,21,32])
b = np.array([1,32,12])

In [192]:
dot = 0

In [193]:
for i,j in zip(a,b):
    dot += i*j

In [194]:
print(dot)


1057

In [195]:
a*b


Out[195]:
array([  1, 672, 384])

In [196]:
print(np.sum(a*b))


1057

In [198]:
print((a*b).sum())


1057

In [199]:
print(np.dot(a,b))


1057

In [200]:
a.dot(b)


Out[200]:
1057

In [201]:
b.dot(a)


Out[201]:
1057

In [202]:
amag = np.sqrt((a*a).sum())

In [203]:
amag


Out[203]:
38.288379438153292

In [204]:
amag = np.linalg.norm(a)

In [205]:
amag


Out[205]:
38.288379438153292

In [208]:
cosAngle = a.dot(b)/(np.linalg.norm(a) * np.linalg.norm(b))

In [209]:
cosAngle


Out[209]:
0.80742231238276452

In [210]:
angle = np.arccos(cosAngle)      #in radians

In [211]:
angle


Out[211]:
0.63102652242709534

In [217]:
# comparing numpy with default python functions

import numpy as np
from datetime import datetime

a = np.random.randn(100)
b = np.random.randn(100)
T = 100000

def slow_dot_product(a,b):
    result = 0
    for e,f in zip(a,b):
        result += e*f

    return result

t0 = datetime.now()
for t in xrange(T):
    slow_dot_product(a,b)
dt1 = datetime.now() - t0

t0 = datetime.now()
for t in xrange(T):
    a.dot(b)
dt2 = datetime.now() - t0

print("dt1/dt2 = ", dt1.total_seconds()/dt2.total_seconds())


('dt1/dt2 = ', 46.810391397849465)

In [218]:
z = np.zeros(10)

In [219]:
z


Out[219]:
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

In [222]:
z = np.zeros((10,10))
z


Out[222]:
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

In [223]:
o = np.ones(10)
o


Out[223]:
array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])

In [224]:
o = np.ones((10,10))
o


Out[224]:
array([[ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.]])

In [228]:
g = np.random.randn(10,10)
g


Out[228]:
array([[ 0.30556723, -0.1531275 ,  1.19291898,  0.48458369, -0.72897641,
         0.28585452, -0.21835187,  0.39588094,  0.65607383,  2.25691262],
       [-0.06112422,  0.96084338, -2.27175282,  0.84154091, -0.45821689,
        -0.25728358,  1.4231254 , -0.22497451, -0.03872762,  0.10148863],
       [ 1.95354128, -1.26067869, -0.48947522, -0.90116875,  0.15685221,
         0.73581953, -1.31858192,  0.43964525, -1.2037121 ,  0.34599614],
       [ 0.7225117 ,  0.93685261,  1.99027255, -0.15483398,  1.00717345,
         0.43961153,  1.35710297,  0.65442207, -0.32017961, -2.00464066],
       [ 2.48467117,  1.35841446, -0.8417843 ,  2.1483636 , -2.04129163,
         2.81500931,  0.40514439, -0.7404707 , -0.69350867,  0.01082942],
       [ 0.32256786,  1.12359219, -0.35952796,  0.91359959,  0.67130493,
         0.11632338,  0.4597404 , -0.26557472, -0.33523262,  1.29439663],
       [-0.74931744,  0.98927081, -1.51396123, -1.56737393, -2.41032701,
        -1.08549081,  1.32096941, -0.46477151,  2.52294382,  1.45610003],
       [-0.90533769, -1.27970592,  0.0955684 ,  0.21185128,  1.37969574,
         0.03830924, -0.56264537,  1.58154679, -0.40898065,  0.40844554],
       [ 0.53490581,  0.61005707,  1.12890134, -0.56691858, -0.21318623,
         0.1370449 , -1.06696474, -1.36791618, -0.01201683, -0.48259429],
       [-0.9295257 , -0.25863103, -1.34124682, -0.95905442, -0.17906502,
        -1.16988623, -0.5008798 ,  0.42884073,  0.56015657, -0.62631918]])

In [229]:
r = np.random.random((10,10))
r


Out[229]:
array([[ 0.04417262,  0.78878866,  0.64738479,  0.41933427,  0.23297596,
         0.60374701,  0.13303651,  0.61399152,  0.06032676,  0.72596034],
       [ 0.65631028,  0.18564054,  0.73036826,  0.1584487 ,  0.86423559,
         0.32833263,  0.64195941,  0.30367103,  0.4910578 ,  0.99453912],
       [ 0.40833616,  0.42310628,  0.31754052,  0.81724942,  0.42830543,
         0.26370308,  0.51605959,  0.80857603,  0.26615087,  0.42996778],
       [ 0.00409192,  0.69426659,  0.47060381,  0.45295957,  0.70751741,
         0.38636617,  0.35533598,  0.60368459,  0.87706015,  0.75117202],
       [ 0.75082573,  0.89923491,  0.52320782,  0.20751083,  0.69220652,
         0.19820559,  0.1613816 ,  0.69758144,  0.46762863,  0.19913196],
       [ 0.77375253,  0.76039427,  0.46083   ,  0.74190246,  0.62274427,
         0.41929709,  0.8541328 ,  0.29924972,  0.44872283,  0.44008921],
       [ 0.889279  ,  0.69877566,  0.00283783,  0.70629851,  0.08700888,
         0.98550186,  0.05826325,  0.00389588,  0.39579188,  0.69555576],
       [ 0.51079061,  0.73912218,  0.74423593,  0.70793354,  0.46654823,
         0.577964  ,  0.91289596,  0.14768685,  0.60055026,  0.2850155 ],
       [ 0.11552274,  0.28190785,  0.73912326,  0.58596188,  0.91393108,
         0.71018806,  0.9863128 ,  0.03205625,  0.12737473,  0.32584894],
       [ 0.0114753 ,  0.6270845 ,  0.16009131,  0.9491194 ,  0.88076893,
         0.82743247,  0.7818142 ,  0.60801523,  0.60050557,  0.47750488]])

In [231]:
print(g.mean())
print(g.var())


0.09207842683
1.14471571591

In [232]:
print(r.mean())
print(r.var())


0.511823563683
0.0748171805665

In [233]:
A = np.array([[1,2],[3,4]])
print(A)


[[1 2]
 [3 4]]

In [234]:
Ainv = np.linalg.inv(A)
print(Ainv)


[[-2.   1. ]
 [ 1.5 -0.5]]

In [236]:
A.dot(Ainv)


Out[236]:
array([[  1.00000000e+00,   0.00000000e+00],
       [  8.88178420e-16,   1.00000000e+00]])

In [237]:
A*Ainv


Out[237]:
array([[-2. ,  2. ],
       [ 4.5, -2. ]])

In [238]:
A.dot(A)


Out[238]:
array([[ 7, 10],
       [15, 22]])

In [239]:
np.linalg.det(A)


Out[239]:
-2.0000000000000004

In [240]:
np.linalg.det(Ainv)


Out[240]:
-0.49999999999999967

In [241]:
np.linalg.det(A.dot(Ainv))


Out[241]:
0.99999999999999956

In [243]:
print(A)
np.diag(A)


[[1 2]
 [3 4]]
Out[243]:
array([1, 4])

In [244]:
np.diag([1,2])


Out[244]:
array([[1, 0],
       [0, 2]])

In [245]:
np.diag([1,2,3])


Out[245]:
array([[1, 0, 0],
       [0, 2, 0],
       [0, 0, 3]])

In [246]:
a = np.array([1,2])
b = np.array([3,4])

In [247]:
print(np.outer(a,b))
print(np.inner(a,b))
print(a.dot(b))


[[3 4]
 [6 8]]
11
11

In [248]:
np.diag(A).sum()


Out[248]:
5

In [249]:
np.trace(A)


Out[249]:
5

In [250]:
x = np.random.randn(100,3)

In [251]:
x


Out[251]:
array([[  1.08825394e+00,   5.09026055e-01,  -8.61654289e-01],
       [ -1.09044329e+00,   4.02756855e-01,   2.19663114e+00],
       [ -1.18715575e+00,   8.62518002e-01,   9.95845730e-01],
       [ -1.71443589e+00,   9.07127073e-01,  -1.01707887e+00],
       [ -7.33422177e-01,   2.58834309e-01,   9.73379163e-01],
       [  7.72904550e-01,   1.74969293e+00,  -4.24550770e-01],
       [ -4.86450082e-01,   6.79040400e-01,  -7.32902189e-01],
       [  4.66321607e-01,  -8.48679044e-01,   1.13598058e+00],
       [  1.84131850e-01,   1.30721579e-01,  -5.73870282e-01],
       [ -2.42389550e-01,   1.28013053e+00,   1.77606962e+00],
       [ -7.53520760e-01,  -1.39147301e+00,   1.56678099e+00],
       [  2.85079164e-01,   1.65257109e+00,   1.71103305e+00],
       [ -1.10078262e-01,  -1.94583679e+00,   5.92135871e-01],
       [  4.39320998e-01,  -1.52226134e+00,  -1.10256422e+00],
       [  8.32422850e-01,   6.39365102e-01,  -6.57658761e-01],
       [ -1.04042345e+00,   5.95342835e-01,   1.54036773e+00],
       [  5.35413936e-01,  -8.45112607e-02,  -3.37407890e-01],
       [ -1.07054786e+00,   5.50216200e-01,   6.55773617e-01],
       [ -1.17004419e-01,  -2.64705498e-02,   7.17473186e-01],
       [  9.16948697e-01,  -8.29012580e-01,  -5.49713920e-02],
       [  3.48705277e-02,   1.23424002e+00,   1.12466864e+00],
       [  9.57399135e-01,   1.67855505e+00,  -5.89936038e-01],
       [  1.04105559e+00,  -5.44113974e-01,  -6.69330632e-01],
       [  1.14188963e+00,   3.30533394e-01,   2.19372183e-01],
       [ -1.38460855e+00,  -1.18257830e+00,  -1.78983375e+00],
       [ -4.58913494e-01,   4.34815630e-01,   5.61504279e-01],
       [  1.62496005e-01,   1.96871056e-01,   2.14496892e-03],
       [ -1.02515676e+00,   2.33375121e+00,   9.17307041e-01],
       [ -1.76899761e+00,  -4.74214352e-02,  -3.48050145e-01],
       [  9.62883596e-02,  -2.09004660e-01,  -4.24739608e-01],
       [  2.39067438e-01,   2.22007232e-01,  -3.17803583e-01],
       [ -2.99980000e-01,  -5.97535269e-01,  -2.93748428e+00],
       [ -1.21421778e+00,   2.37908091e+00,   7.63804765e-02],
       [ -1.74800491e+00,  -8.25279531e-01,  -8.25016849e-01],
       [  1.71725702e+00,   1.02141312e+00,  -8.17836573e-01],
       [ -1.29386302e+00,   2.44979904e-02,  -1.70219415e+00],
       [ -5.48225959e-01,   1.21169559e+00,   2.14289366e+00],
       [  2.28749382e-01,  -2.55327664e-01,  -2.06879509e-01],
       [  7.44109207e-02,   1.21544396e+00,   1.32951020e+00],
       [  6.18850492e-01,  -1.19788631e+00,   8.81548528e-01],
       [  8.21189012e-01,  -9.86491225e-01,  -4.06187915e-01],
       [ -7.83326711e-01,   1.33857791e+00,  -5.19937459e-01],
       [  5.59663758e-01,  -6.89881551e-01,   1.27389263e+00],
       [  4.95660918e-01,   3.16726552e-01,  -6.70366273e-01],
       [  1.71282754e+00,   1.23751515e+00,   7.93652710e-01],
       [  5.61370221e-01,   1.54954132e-01,   1.67046924e-05],
       [ -3.94918130e-02,  -7.23448077e-01,  -2.58998930e-01],
       [  1.25265299e+00,  -2.65666659e-01,  -5.18409446e-01],
       [ -3.64227669e-01,   3.30811833e-01,  -8.21136184e-01],
       [ -3.67064053e-01,   1.47762661e+00,   3.14226405e-01],
       [  7.31779009e-01,   4.13983472e-01,   6.46001676e-01],
       [ -6.97940383e-01,  -6.81552143e-01,  -7.67531459e-01],
       [  9.47797045e-01,  -1.15422934e+00,   9.31724657e-01],
       [ -1.95105239e-01,  -7.47831804e-02,  -2.72917381e-01],
       [  4.10114413e-01,  -1.14998183e+00,  -7.62549285e-03],
       [  9.96168040e-01,  -5.88382956e-01,   9.00266630e-02],
       [ -1.81081273e+00,  -2.15478567e-01,  -1.20243966e+00],
       [ -6.81169838e-01,  -1.53639375e+00,  -1.17603326e+00],
       [ -2.42499060e-01,   3.82855158e-01,   9.18362676e-03],
       [ -7.15150827e-01,   5.15101463e-02,   5.87062662e-02],
       [ -5.68682454e-01,   1.71025383e+00,  -1.01190994e+00],
       [  2.86473732e-01,   3.76477081e-01,   1.40086558e+00],
       [  1.19358960e+00,  -6.41625670e-02,   6.00678567e-02],
       [ -2.91614119e-01,  -7.05125260e-01,   4.55361633e-02],
       [ -4.74912280e-01,  -7.19722875e-01,   1.43201724e+00],
       [  2.31331367e+00,   8.13290098e-01,  -8.01012149e-02],
       [  7.98590306e-01,   4.37559652e-01,   7.09215804e-01],
       [  4.48173727e-01,   5.72662771e-03,   4.34495468e-01],
       [  2.34242419e+00,  -5.07799163e-01,   1.10845818e+00],
       [  1.23770111e+00,   1.24119585e+00,  -4.56940897e-01],
       [ -1.36394895e+00,  -5.75825599e-01,  -8.42952510e-01],
       [  1.15796937e+00,   9.27492222e-01,   8.45004695e-01],
       [  7.74567277e-01,   1.23724190e+00,  -1.48933190e+00],
       [  5.83089405e-01,   1.09072512e+00,  -3.48527226e-02],
       [  5.96762392e-03,  -3.40453299e-01,   1.39865495e-01],
       [  7.04555532e-01,   2.45054592e+00,   3.93892076e-01],
       [  5.09714398e-01,   9.77676614e-02,   3.66918752e-01],
       [  7.97101514e-01,   1.65666501e+00,  -9.60449910e-01],
       [ -9.10545768e-02,  -4.97353853e-01,   3.88810859e-01],
       [ -8.89213089e-01,  -3.96153642e-01,  -1.79147497e-01],
       [  9.09283946e-01,   1.21948995e+00,  -4.62802184e-01],
       [  2.11567822e-01,  -3.76257193e-01,  -9.25428459e-01],
       [  4.05251709e-01,   1.46422817e+00,   1.15509412e+00],
       [ -1.07875023e+00,  -5.61126143e-02,   1.55447062e+00],
       [  5.68602737e-01,  -2.48457481e-02,  -5.48958938e-01],
       [ -1.89820533e-01,   1.26220016e+00,  -1.20643832e+00],
       [ -2.84644474e-01,  -4.17556427e-01,  -1.70045724e+00],
       [  4.03852726e-01,   1.32686856e-01,  -1.55459985e+00],
       [  1.02285715e+00,   3.81751219e-01,  -1.21515104e+00],
       [ -2.01687781e+00,   1.25801019e+00,  -9.27327613e-02],
       [ -1.70048460e-01,   1.19798155e+00,   3.62938869e-02],
       [  7.24915816e-01,  -1.47000885e+00,   1.35305874e+00],
       [  1.30194119e-01,   4.75509442e-01,   1.21009352e+00],
       [ -4.00374214e-01,  -1.27958085e+00,   1.35854893e+00],
       [ -7.29953648e-01,   4.20230604e-01,   1.28083725e-01],
       [  8.88112913e-01,  -7.15555464e-01,  -1.32901313e+00],
       [ -5.66888051e-01,   5.15491506e-01,   1.20285910e+00],
       [  7.05572026e-01,  -4.70515475e-01,   1.39120333e+00],
       [  1.46236507e-01,  -7.64100388e-01,  -2.95213862e-01],
       [ -1.99682894e-02,  -5.05792609e-01,   8.24309695e-01]])

In [252]:
cov = np.cov(x)
cov


Out[252]:
array([[ 1.00273527, -1.62220414, -0.93777174, ..., -0.53458614,
         0.12423111, -0.53133445],
       [-1.62220414,  2.70874832,  1.74590578, ...,  0.6395461 ,
        -0.32821199,  0.73930133],
       [-0.93777174,  1.74590578,  1.4974057 , ..., -0.11094046,
        -0.46117748,  0.17076971],
       ..., 
       [-0.53458614,  0.6395461 , -0.11094046, ...,  0.88654484,
         0.27348309,  0.60441863],
       [ 0.12423111, -0.32821199, -0.46117748, ...,  0.27348309,
         0.20724104,  0.11553734],
       [-0.53133445,  0.73930133,  0.17076971, ...,  0.60441863,
         0.11553734,  0.45300045]])

In [253]:
cov.shape


Out[253]:
(100, 100)

In [254]:
cov = np.cov(x.T)

In [255]:
cov


Out[255]:
array([[ 0.8028042 ,  0.01146894,  0.01574303],
       [ 0.01146894,  0.90513939,  0.06903582],
       [ 0.01574303,  0.06903582,  0.98193194]])

In [256]:
cov.shape


Out[256]:
(3, 3)

In [257]:
np.linalg.eigh(cov)


Out[257]:
(array([ 0.80105047,  0.8645972 ,  1.02422786]),
 array([[ 0.99574687,  0.02968233,  0.08721891],
        [-0.06994009,  0.85975936,  0.50588756],
        [-0.05997135, -0.50983605,  0.85817868]]))

In [258]:
np.linalg.eig(cov)


Out[258]:
(array([ 1.02422786,  0.80105047,  0.8645972 ]),
 array([[ 0.08721891,  0.99574687, -0.02968233],
        [ 0.50588756, -0.06994009, -0.85975936],
        [ 0.85817868, -0.05997135,  0.50983605]]))

In [260]:
#linear system
# Ax = b
#=> A-1.A.x = 0 
#=> x = A-1.b

In [261]:
A


Out[261]:
array([[1, 2],
       [3, 4]])

In [262]:
b


Out[262]:
array([3, 4])

In [263]:
b = np.array([1,2])

In [264]:
b


Out[264]:
array([1, 2])

In [265]:
x = np.linalg.inv(A).dot(b)
print(x)


[ 0.   0.5]

In [267]:
x = np.linalg.solve(A,b)
print(x)


[ 0.   0.5]

In [268]:
A = np.array([[1,1],[1.5,4]])
b = np.array([2200,5050])

x = np.linalg.solve(A,b)
print(x)


[ 1500.   700.]

In [271]:
Y = []
Y


Out[271]:
[]

In [278]:
Y = []
for line in open("data_2d.csv"):
    row = line.split(',')
    sample = map(float, row)
    Y.append(sample)

Y = np.array(Y)
print(Y)


[[  1.79302012e+01   9.45205920e+01   3.20259530e+02]
 [  9.71446972e+01   6.95932820e+01   4.04634472e+02]
 [  8.17759008e+01   5.73764810e+00   1.81485108e+02]
 [  5.58543424e+01   7.03259017e+01   3.21773638e+02]
 [  4.93665500e+01   7.51140402e+01   3.22465486e+02]
 [  3.19270247e+00   2.92562989e+01   9.46188109e+01]
 [  4.92007841e+01   8.61444385e+01   3.56348093e+02]
 [  2.18828039e+01   4.68415052e+01   1.81653769e+02]
 [  7.95098627e+01   8.73973555e+01   4.23557743e+02]
 [  8.81538875e+01   6.52056419e+01   3.69229245e+02]
 [  6.07438543e+01   9.99576339e+01   4.27605804e+02]
 [  6.74155819e+01   5.03683096e+01   2.92471822e+02]
 [  4.83181158e+01   9.91289531e+01   3.95529811e+02]
 [  2.88299720e+01   8.71849489e+01   3.19031348e+02]
 [  4.38537427e+01   6.44736391e+01   2.87428144e+02]
 [  2.53136941e+01   8.35452943e+01   2.92768909e+02]
 [  1.08077267e+01   4.56955686e+01   1.59663308e+02]
 [  9.83657459e+01   8.26973935e+01   4.38798964e+02]
 [  2.91469100e+01   6.63651068e+01   2.50986309e+02]
 [  6.51003019e+01   3.33538835e+01   2.31711508e+02]
 [  2.46441135e+01   3.95400527e+01   1.63398161e+02]
 [  3.75598049e+01   1.34572784e+00   8.34801551e+01]
 [  8.81645062e+01   9.51536626e+01   4.66265806e+02]
 [  1.38346208e+01   2.54940482e+01   1.00886430e+02]
 [  6.44108437e+01   7.72598381e+01   3.65641048e+02]
 [  6.89259918e+01   9.74536008e+01   4.26140015e+02]
 [  3.94884422e+01   5.08561282e+01   2.35532389e+02]
 [  5.24631777e+01   5.97765097e+01   2.83291640e+02]
 [  4.84847870e+01   6.69703542e+01   2.98581440e+02]
 [  8.06208781e+00   9.82426001e+01   3.09234109e+02]
 [  3.27318877e+01   1.88535355e+01   1.29610139e+02]
 [  1.16523788e+01   6.62645117e+01   2.24150542e+02]
 [  1.37303535e+01   7.04725091e+01   2.35305666e+02]
 [  8.18555177e+00   4.18519894e+01   1.53484189e+02]
 [  5.36098761e+01   9.45601216e+01   3.94939444e+02]
 [  9.53686099e+01   4.72955070e+01   3.36126739e+02]
 [  8.73336092e+01   9.38039343e+01   4.49363352e+02]
 [  6.63576111e+01   8.18475513e+01   3.87014816e+02]
 [  1.97547175e+01   6.55233009e+01   2.40389442e+02]
 [  2.11334405e+01   4.74371820e+01   1.77148281e+02]
 [  2.23738648e+01   2.59556275e+01   1.19611258e+02]
 [  9.39904041e+01   1.27890520e-01   1.96716167e+02]
 [  8.67201981e+01   1.84137668e+01   2.36260808e+02]
 [  9.89983730e+01   6.02312657e+01   3.84381345e+02]
 [  3.59396564e+00   9.62522173e+01   2.93237183e+02]
 [  1.51023634e+01   9.25569036e+01   3.04890883e+02]
 [  9.78341408e+01   2.02390810e+00   2.01293598e+02]
 [  1.99382197e+01   4.67782735e+01   1.70610093e+02]
 [  3.03735111e+01   5.87775252e+01   2.42373484e+02]
 [  7.32928831e+01   6.76696278e+01   3.53082991e+02]
 [  5.22309009e+01   8.19024483e+01   3.48725689e+02]
 [  8.64295761e+01   6.65402276e+01   3.65959971e+02]
 [  9.34008021e+01   1.80752459e+01   2.35472382e+02]
 [  1.32134601e+01   9.14888588e+01   3.00606878e+02]
 [  4.59346270e+00   4.63359315e+01   1.45818745e+02]
 [  1.56692916e+01   3.55437440e+01   1.38880335e+02]
 [  5.29593598e+01   6.87202096e+01   3.17163708e+02]
 [  5.68175212e+01   4.75727319e+01   2.54903631e+02]
 [  5.11335431e+01   7.80421675e+01   3.34584334e+02]
 [  7.86216472e+00   1.77290818e+01   6.93555888e+01]
 [  5.46986037e+01   9.27445841e+01   3.86859937e+02]
 [  8.63990630e+01   4.18886946e+01   2.94871714e+02]
 [  1.19475060e+01   4.29613867e+01   1.56754220e+02]
 [  7.03584011e+01   8.37062345e+01   3.91806135e+02]
 [  2.90223663e+01   8.43277831e+01   3.19310463e+02]
 [  4.27594799e+01   9.74933261e+01   3.76291589e+02]
 [  9.62156564e+01   2.58342826e+01   2.80617044e+02]
 [  5.32277277e+01   2.79055086e+01   1.94430465e+02]
 [  3.03609897e+01   9.39644215e-01   6.96488632e+01]
 [  8.32775654e+01   7.31793486e+01   3.84597185e+02]
 [  3.01876925e+01   7.14653860e+00   8.95390084e+01]
 [  1.17884185e+01   5.16977608e+01   1.81550683e+02]
 [  1.82924240e+01   6.19779760e+01   2.24773383e+02]
 [  9.67126677e+01   9.02910151e+00   2.19567094e+02]
 [  3.10127387e+01   7.82833825e+01   2.98490216e+02]
 [  1.13972608e+01   6.17286932e+01   1.99944045e+02]
 [  1.73925558e+01   4.24114086e+00   4.39156924e+01]
 [  7.21826937e+01   3.45390722e+01   2.56068378e+02]
 [  7.39800208e+01   3.71649344e+00   1.59372581e+02]
 [  9.44930584e+01   8.84171970e+01   4.47132704e+02]
 [  8.45628207e+01   2.02411622e+01   2.33078830e+02]
 [  5.17424740e+01   1.10097480e+01   1.31070180e+02]
 [  5.37485904e+01   6.00251023e+01   2.98814333e+02]
 [  8.50508348e+01   9.57369970e+01   4.51803523e+02]
 [  4.67772505e+01   9.02022062e+01   3.68366436e+02]
 [  4.97584342e+01   5.28344944e+01   2.54706774e+02]
 [  2.41192565e+01   4.21028108e+01   1.68308433e+02]
 [  2.72015765e+01   2.99787493e+01   1.46342260e+02]
 [  7.00959617e+00   5.58760584e+01   1.76810149e+02]
 [  9.76469497e+01   8.14762513e+00   2.19160280e+02]
 [  1.38298251e+00   8.49440869e+01   2.52905653e+02]
 [  2.23235304e+01   2.75150750e+01   1.27570479e+02]
 [  4.50454062e+01   9.35204022e+01   3.75822340e+02]
 [  4.01639915e+01   1.61699235e-01   8.03890193e+01]
 [  5.31827398e+01   8.17031616e+00   1.42718183e+02]
 [  4.64567792e+01   8.20001709e+01   3.36876154e+02]
 [  7.71303007e+01   9.51887595e+01   4.38460586e+02]
 [  6.86006076e+01   7.25711807e+01   3.55900287e+02]
 [  4.16938871e+01   6.92411260e+01   2.84834637e+02]
 [  4.14266940e+00   5.22547264e+01   1.68034401e+02]]

In [279]:
Y.shape


Out[279]:
(100, 3)

In [281]:
import matplotlib.pyplot as plt

In [284]:
import pandas as pd


---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-284-7dd3504c366f> in <module>()
----> 1 import pandas as pd

/usr/local/lib/python2.7/dist-packages/pandas/__init__.py in <module>()
     33                       "pandas from the source directory, you may need to run "
     34                       "'python setup.py build_ext --inplace --force' to build "
---> 35                       "the C extensions first.".format(module))
     36 
     37 from datetime import datetime

ImportError: C extension: iNaT not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace --force' to build the C extensions first.

In [1]:
import pandas as pd

In [2]:
pd.show_versions()


INSTALLED VERSIONS
------------------
commit: None
python: 2.7.12.final.0
python-bits: 64
OS: Linux
OS-release: 4.13.0-26-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_IN
LOCALE: None.None

pandas: 0.20.2
pytest: 2.8.7
pip: 9.0.1
setuptools: 20.7.0
Cython: None
numpy: 1.14.0
scipy: 1.0.0
xarray: None
IPython: 5.5.0
sphinx: None
patsy: 0.4.1
dateutil: 2.6.1
pytz: 2017.3
blosc: None
bottleneck: None
tables: 3.2.2
numexpr: 2.6.4
feather: None
matplotlib: 2.1.0
openpyxl: 2.3.0
xlrd: 0.9.4
xlwt: 0.7.5
xlsxwriter: None
lxml: 3.5.0
bs4: 4.4.1
html5lib: 0.9999999
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: 2.9.6
s3fs: None
pandas_gbq: None
pandas_datareader: None

In [1]:
import pandas as pd

In [2]:
Y = pd.read_csv("data_2d.csv", header=None)

In [3]:
Y


Out[3]:
0 1 2
0 17.930201 94.520592 320.259530
1 97.144697 69.593282 404.634472
2 81.775901 5.737648 181.485108
3 55.854342 70.325902 321.773638
4 49.366550 75.114040 322.465486
5 3.192702 29.256299 94.618811
6 49.200784 86.144439 356.348093
7 21.882804 46.841505 181.653769
8 79.509863 87.397356 423.557743
9 88.153887 65.205642 369.229245
10 60.743854 99.957634 427.605804
11 67.415582 50.368310 292.471822
12 48.318116 99.128953 395.529811
13 28.829972 87.184949 319.031348
14 43.853743 64.473639 287.428144
15 25.313694 83.545294 292.768909
16 10.807727 45.695569 159.663308
17 98.365746 82.697394 438.798964
18 29.146910 66.365107 250.986309
19 65.100302 33.353883 231.711508
20 24.644113 39.540053 163.398161
21 37.559805 1.345728 83.480155
22 88.164506 95.153663 466.265806
23 13.834621 25.494048 100.886430
24 64.410844 77.259838 365.641048
25 68.925992 97.453601 426.140015
26 39.488442 50.856128 235.532389
27 52.463178 59.776510 283.291640
28 48.484787 66.970354 298.581440
29 8.062088 98.242600 309.234109
... ... ... ...
70 30.187692 7.146539 89.539008
71 11.788418 51.697761 181.550683
72 18.292424 61.977976 224.773383
73 96.712668 9.029102 219.567094
74 31.012739 78.283382 298.490216
75 11.397261 61.728693 199.944045
76 17.392556 4.241141 43.915692
77 72.182694 34.539072 256.068378
78 73.980021 3.716493 159.372581
79 94.493058 88.417197 447.132704
80 84.562821 20.241162 233.078830
81 51.742474 11.009748 131.070180
82 53.748590 60.025102 298.814333
83 85.050835 95.736997 451.803523
84 46.777250 90.202206 368.366436
85 49.758434 52.834494 254.706774
86 24.119257 42.102811 168.308433
87 27.201576 29.978749 146.342260
88 7.009596 55.876058 176.810149
89 97.646950 8.147625 219.160280
90 1.382983 84.944087 252.905653
91 22.323530 27.515075 127.570479
92 45.045406 93.520402 375.822340
93 40.163991 0.161699 80.389019
94 53.182740 8.170316 142.718183
95 46.456779 82.000171 336.876154
96 77.130301 95.188759 438.460586
97 68.600608 72.571181 355.900287
98 41.693887 69.241126 284.834637
99 4.142669 52.254726 168.034401

100 rows × 3 columns


In [4]:
type(Y)


Out[4]:
pandas.core.frame.DataFrame

In [5]:
Y.info()


<class 'pandas.core.frame.DataFrame'>
RangeIndex: 100 entries, 0 to 99
Data columns (total 3 columns):
0    100 non-null float64
1    100 non-null float64
2    100 non-null float64
dtypes: float64(3)
memory usage: 2.4 KB

In [6]:
Y.head()


Out[6]:
0 1 2
0 17.930201 94.520592 320.259530
1 97.144697 69.593282 404.634472
2 81.775901 5.737648 181.485108
3 55.854342 70.325902 321.773638
4 49.366550 75.114040 322.465486

In [7]:
Y.head(9)


Out[7]:
0 1 2
0 17.930201 94.520592 320.259530
1 97.144697 69.593282 404.634472
2 81.775901 5.737648 181.485108
3 55.854342 70.325902 321.773638
4 49.366550 75.114040 322.465486
5 3.192702 29.256299 94.618811
6 49.200784 86.144439 356.348093
7 21.882804 46.841505 181.653769
8 79.509863 87.397356 423.557743

In [8]:
Y[0]


Out[8]:
0     17.930201
1     97.144697
2     81.775901
3     55.854342
4     49.366550
5      3.192702
6     49.200784
7     21.882804
8     79.509863
9     88.153887
10    60.743854
11    67.415582
12    48.318116
13    28.829972
14    43.853743
15    25.313694
16    10.807727
17    98.365746
18    29.146910
19    65.100302
20    24.644113
21    37.559805
22    88.164506
23    13.834621
24    64.410844
25    68.925992
26    39.488442
27    52.463178
28    48.484787
29     8.062088
        ...    
70    30.187692
71    11.788418
72    18.292424
73    96.712668
74    31.012739
75    11.397261
76    17.392556
77    72.182694
78    73.980021
79    94.493058
80    84.562821
81    51.742474
82    53.748590
83    85.050835
84    46.777250
85    49.758434
86    24.119257
87    27.201576
88     7.009596
89    97.646950
90     1.382983
91    22.323530
92    45.045406
93    40.163991
94    53.182740
95    46.456779
96    77.130301
97    68.600608
98    41.693887
99     4.142669
Name: 0, Length: 100, dtype: float64

In [9]:
type(Y[0])


Out[9]:
pandas.core.series.Series

In [10]:
Y.iloc[0]


Out[10]:
0     17.930201
1     94.520592
2    320.259530
Name: 0, dtype: float64

In [12]:
Y.ix[0]


Out[12]:
0     17.930201
1     94.520592
2    320.259530
Name: 0, dtype: float64

In [13]:
Y[[0,2]]


Out[13]:
0 2
0 17.930201 320.259530
1 97.144697 404.634472
2 81.775901 181.485108
3 55.854342 321.773638
4 49.366550 322.465486
5 3.192702 94.618811
6 49.200784 356.348093
7 21.882804 181.653769
8 79.509863 423.557743
9 88.153887 369.229245
10 60.743854 427.605804
11 67.415582 292.471822
12 48.318116 395.529811
13 28.829972 319.031348
14 43.853743 287.428144
15 25.313694 292.768909
16 10.807727 159.663308
17 98.365746 438.798964
18 29.146910 250.986309
19 65.100302 231.711508
20 24.644113 163.398161
21 37.559805 83.480155
22 88.164506 466.265806
23 13.834621 100.886430
24 64.410844 365.641048
25 68.925992 426.140015
26 39.488442 235.532389
27 52.463178 283.291640
28 48.484787 298.581440
29 8.062088 309.234109
... ... ...
70 30.187692 89.539008
71 11.788418 181.550683
72 18.292424 224.773383
73 96.712668 219.567094
74 31.012739 298.490216
75 11.397261 199.944045
76 17.392556 43.915692
77 72.182694 256.068378
78 73.980021 159.372581
79 94.493058 447.132704
80 84.562821 233.078830
81 51.742474 131.070180
82 53.748590 298.814333
83 85.050835 451.803523
84 46.777250 368.366436
85 49.758434 254.706774
86 24.119257 168.308433
87 27.201576 146.342260
88 7.009596 176.810149
89 97.646950 219.160280
90 1.382983 252.905653
91 22.323530 127.570479
92 45.045406 375.822340
93 40.163991 80.389019
94 53.182740 142.718183
95 46.456779 336.876154
96 77.130301 438.460586
97 68.600608 355.900287
98 41.693887 284.834637
99 4.142669 168.034401

100 rows × 2 columns


In [14]:
Y[ Y[0] < 5 ]


Out[14]:
0 1 2
5 3.192702 29.256299 94.618811
44 3.593966 96.252217 293.237183
54 4.593463 46.335932 145.818745
90 1.382983 84.944087 252.905653
99 4.142669 52.254726 168.034401

In [15]:
Y[0] < 5


Out[15]:
0     False
1     False
2     False
3     False
4     False
5      True
6     False
7     False
8     False
9     False
10    False
11    False
12    False
13    False
14    False
15    False
16    False
17    False
18    False
19    False
20    False
21    False
22    False
23    False
24    False
25    False
26    False
27    False
28    False
29    False
      ...  
70    False
71    False
72    False
73    False
74    False
75    False
76    False
77    False
78    False
79    False
80    False
81    False
82    False
83    False
84    False
85    False
86    False
87    False
88    False
89    False
90     True
91    False
92    False
93    False
94    False
95    False
96    False
97    False
98    False
99     True
Name: 0, Length: 100, dtype: bool

In [16]:
type(Y[0] < 5)


Out[16]:
pandas.core.series.Series

In [17]:
df = pd.read_csv("international-airline-passengers.csv", engine="python", skipfooter=3)

In [18]:
df


Out[18]:
Month International airline passengers: monthly totals in thousands. Jan 49 ? Dec 60
0 1949-01 112
1 1949-02 118
2 1949-03 132
3 1949-04 129
4 1949-05 121
5 1949-06 135
6 1949-07 148
7 1949-08 148
8 1949-09 136
9 1949-10 119
10 1949-11 104
11 1949-12 118
12 1950-01 115
13 1950-02 126
14 1950-03 141
15 1950-04 135
16 1950-05 125
17 1950-06 149
18 1950-07 170
19 1950-08 170
20 1950-09 158
21 1950-10 133
22 1950-11 114
23 1950-12 140
24 1951-01 145
25 1951-02 150
26 1951-03 178
27 1951-04 163
28 1951-05 172
29 1951-06 178
... ... ...
114 1958-07 491
115 1958-08 505
116 1958-09 404
117 1958-10 359
118 1958-11 310
119 1958-12 337
120 1959-01 360
121 1959-02 342
122 1959-03 406
123 1959-04 396
124 1959-05 420
125 1959-06 472
126 1959-07 548
127 1959-08 559
128 1959-09 463
129 1959-10 407
130 1959-11 362
131 1959-12 405
132 1960-01 417
133 1960-02 391
134 1960-03 419
135 1960-04 461
136 1960-05 472
137 1960-06 535
138 1960-07 622
139 1960-08 606
140 1960-09 508
141 1960-10 461
142 1960-11 390
143 1960-12 432

144 rows × 2 columns


In [20]:
df.columns


Out[20]:
Index([u'Month', u'International airline passengers: monthly totals in thousands. Jan 49 ? Dec 60'], dtype='object')

In [21]:
df.columns = ['month', 'passangers']

In [22]:
df.columns


Out[22]:
Index([u'month', u'passangers'], dtype='object')

In [23]:
df


Out[23]:
month passangers
0 1949-01 112
1 1949-02 118
2 1949-03 132
3 1949-04 129
4 1949-05 121
5 1949-06 135
6 1949-07 148
7 1949-08 148
8 1949-09 136
9 1949-10 119
10 1949-11 104
11 1949-12 118
12 1950-01 115
13 1950-02 126
14 1950-03 141
15 1950-04 135
16 1950-05 125
17 1950-06 149
18 1950-07 170
19 1950-08 170
20 1950-09 158
21 1950-10 133
22 1950-11 114
23 1950-12 140
24 1951-01 145
25 1951-02 150
26 1951-03 178
27 1951-04 163
28 1951-05 172
29 1951-06 178
... ... ...
114 1958-07 491
115 1958-08 505
116 1958-09 404
117 1958-10 359
118 1958-11 310
119 1958-12 337
120 1959-01 360
121 1959-02 342
122 1959-03 406
123 1959-04 396
124 1959-05 420
125 1959-06 472
126 1959-07 548
127 1959-08 559
128 1959-09 463
129 1959-10 407
130 1959-11 362
131 1959-12 405
132 1960-01 417
133 1960-02 391
134 1960-03 419
135 1960-04 461
136 1960-05 472
137 1960-06 535
138 1960-07 622
139 1960-08 606
140 1960-09 508
141 1960-10 461
142 1960-11 390
143 1960-12 432

144 rows × 2 columns


In [25]:
df['passangers']


Out[25]:
0      112
1      118
2      132
3      129
4      121
5      135
6      148
7      148
8      136
9      119
10     104
11     118
12     115
13     126
14     141
15     135
16     125
17     149
18     170
19     170
20     158
21     133
22     114
23     140
24     145
25     150
26     178
27     163
28     172
29     178
      ... 
114    491
115    505
116    404
117    359
118    310
119    337
120    360
121    342
122    406
123    396
124    420
125    472
126    548
127    559
128    463
129    407
130    362
131    405
132    417
133    391
134    419
135    461
136    472
137    535
138    622
139    606
140    508
141    461
142    390
143    432
Name: passangers, Length: 144, dtype: int64

In [27]:
df.passangers


Out[27]:
0      112
1      118
2      132
3      129
4      121
5      135
6      148
7      148
8      136
9      119
10     104
11     118
12     115
13     126
14     141
15     135
16     125
17     149
18     170
19     170
20     158
21     133
22     114
23     140
24     145
25     150
26     178
27     163
28     172
29     178
      ... 
114    491
115    505
116    404
117    359
118    310
119    337
120    360
121    342
122    406
123    396
124    420
125    472
126    548
127    559
128    463
129    407
130    362
131    405
132    417
133    391
134    419
135    461
136    472
137    535
138    622
139    606
140    508
141    461
142    390
143    432
Name: passangers, Length: 144, dtype: int64

In [28]:
df['ones'] = 1

In [29]:
df.head()


Out[29]:
month passangers ones
0 1949-01 112 1
1 1949-02 118 1
2 1949-03 132 1
3 1949-04 129 1
4 1949-05 121 1

In [34]:
from datetime import datetime
datetime.strptime("2018-05", "%Y-%m")
df['x1x2'] = df.apply(lambda row: datetime.strptime(row["month"], "%Y-%m"), axis=1)

In [35]:
df.head()


Out[35]:
month passangers ones x1x2
0 1949-01 112 1 1949-01-01
1 1949-02 118 1 1949-02-01
2 1949-03 132 1 1949-03-01
3 1949-04 129 1 1949-04-01
4 1949-05 121 1 1949-05-01

In [36]:
df.info()


<class 'pandas.core.frame.DataFrame'>
RangeIndex: 144 entries, 0 to 143
Data columns (total 4 columns):
month         144 non-null object
passangers    144 non-null int64
ones          144 non-null int64
x1x2          144 non-null datetime64[ns]
dtypes: datetime64[ns](1), int64(2), object(1)
memory usage: 4.6+ KB

In [38]:
t1 = pd.read_csv("table1.csv")
t2 = pd.read_csv("table2.csv")

In [39]:
t1


Out[39]:
user_id email age
0 1 alice@gmail.com 20
1 2 bob@gmail.com 25
2 3 carol@gmail.com 30

In [40]:
t2


Out[40]:
user_id ad_id click
0 1 1 1
1 1 2 0
2 1 5 0
3 2 3 0
4 2 4 1
5 2 1 0
6 3 2 0
7 3 1 0
8 3 3 0
9 3 4 0
10 3 5 1

In [41]:
type(t1)


Out[41]:
pandas.core.frame.DataFrame

In [44]:
m = pd.merge(t1,t2,on='user_id')

In [45]:
m


Out[45]:
user_id email age ad_id click
0 1 alice@gmail.com 20 1 1
1 1 alice@gmail.com 20 2 0
2 1 alice@gmail.com 20 5 0
3 2 bob@gmail.com 25 3 0
4 2 bob@gmail.com 25 4 1
5 2 bob@gmail.com 25 1 0
6 3 carol@gmail.com 30 2 0
7 3 carol@gmail.com 30 1 0
8 3 carol@gmail.com 30 3 0
9 3 carol@gmail.com 30 4 0
10 3 carol@gmail.com 30 5 1

In [46]:
t1.merge(t2, on="user_id")


Out[46]:
user_id email age ad_id click
0 1 alice@gmail.com 20 1 1
1 1 alice@gmail.com 20 2 0
2 1 alice@gmail.com 20 5 0
3 2 bob@gmail.com 25 3 0
4 2 bob@gmail.com 25 4 1
5 2 bob@gmail.com 25 1 0
6 3 carol@gmail.com 30 2 0
7 3 carol@gmail.com 30 1 0
8 3 carol@gmail.com 30 3 0
9 3 carol@gmail.com 30 4 0
10 3 carol@gmail.com 30 5 1

In [50]:
import numpy as np
import matplotlib.pyplot as plt

In [82]:
x = np.linspace(0,10,100)
y = np.sin(x)

plt.plot(x,y)
plt.xlabel('time')
plt.ylabel('sine')
plt.title('Cool function')
plt.show()



In [83]:
import pandas as pd
d1 = pd.read_csv("data_1d.csv").as_matrix()

In [84]:
x1 = d1[:,0]
y1 = d1[:,1]

In [85]:
plt.scatter(x1,y1)
plt.show()



In [86]:
x_line = np.linspace(0,100,100)
y_line = 2*x_line + 1
plt.scatter(x1, y1)
plt.plot(x_line, y_line)
plt.show()



In [90]:
plt.hist(x1)
plt.show()



In [92]:
plt.hist(y1)
plt.show()



In [94]:
plt.hist2d(x1,y1)
plt.show()



In [96]:
R = np.random.random(10000)
plt.hist(R)
plt.show()



In [97]:
plt.hist(R, bins=20)
plt.show()



In [98]:
y_actual = 2*x1 + 1
res = y1 - y_actual
plt.hist(res)
plt.show()



In [1]:
import numpy as np

In [2]:
r = np.random.randn(10000, 2)

In [3]:
import matplotlib.pyplot as plt

In [4]:
plt.scatter(r[:,0], r[:,1])
plt.show()



In [5]:
r[:,1] = 5*r[:,1] + 2

In [7]:
plt.scatter(r[:,0], r[:,1])
plt.axis('equal')
plt.show()



In [8]:
cov = np.array([[1, 0.8], [0.8, 3]])

In [9]:
from scipy.stats import multivariate_normal as mvn

In [10]:
mu = np.array([0,2])
mu


Out[10]:
array([0, 2])

In [11]:
r = mvn.rvs(mean = mu, cov=cov, size=1000)

In [25]:
plt.scatter(r[:,0], r[:,1])
plt.axis('equal')
plt.show()



In [26]:
r = np.random.multivariate_normal(mean = mu, cov=cov, size=1000)
plt.scatter(r[:,0], r[:,1])
plt.axis('equal')
plt.show()



In [28]:
x = np.linspace(0, 100, 10000)
y = np.sin(x) + np.sin(3*x) + np.sin(5*x)
plt.plot(y)
plt.show()



In [30]:
Y = np.fft.fft(y)
plt.plot(np.abs(Y))
plt.show()



In [1]:
s = """w'o"w"""

In [2]:
repr(s)


Out[2]:
'\'w\\\'o"w\''

In [3]:
str(s)


Out[3]:
'w\'o"w'

In [5]:
eval(str(s)) == s


  File "<string>", line 1
    w'o"w
        ^
SyntaxError: EOL while scanning string literal

In [6]:
eval(repr(s)) == s


Out[6]:
True

In [7]:
eval(repr(s))


Out[7]:
'w\'o"w'

In [8]:
s


Out[8]:
'w\'o"w'

In [9]:
str(s)


Out[9]:
'w\'o"w'

In [10]:
eval(str(s))


  File "<string>", line 1
    w'o"w
        ^
SyntaxError: EOL while scanning string literal

In [12]:
type(str(s))


Out[12]:
str

In [13]:
type(repr(s))


Out[13]:
str

In [14]:
type(s)


Out[14]:
str

In [15]:
import datetime

In [16]:
today = datetime.datetime.now()

In [17]:
str(today)


Out[17]:
'2018-01-22 12:39:40.143122'

In [18]:
repr(today)


Out[18]:
'datetime.datetime(2018, 1, 22, 12, 39, 40, 143122)'

In [19]:
eval(str(today)) == eval(repr(today))


  File "<string>", line 1
    2018-01-22 12:39:40.143122
                ^
SyntaxError: invalid syntax

In [20]:
# when writing a class we can override these methods
# to do whatever we want:

In [40]:
class Represent(object):
    
    def __init__(self,x,y):
        self.x, self.y = x,y
    
    def __repr__(self):
        return "Represent(x={}, y=\"{}\")".format(self.x, self.y)
    
    def __str__(self):
        return "Representing x as {} and y as {}".format(self.x, self.y)

In [41]:
r = Represent(1, "Rustom")

In [42]:
print(r)


Representing x as 1 and y as Rustom

In [43]:
print(r.__repr__)


<bound method Represent.__repr__ of Represent(x=1, y="Rustom")>

In [44]:
rep = r.__repr__()

In [45]:
print(rep)


Represent(x=1, y="Rustom")

In [46]:
r2 = eval(rep)

In [47]:
print(r2)


Representing x as 1 and y as Rustom

In [49]:
type(r)


Out[49]:
__main__.Represent

In [50]:
type(r2)


Out[50]:
__main__.Represent

In [51]:
print(r2 == r)


False

In [53]:
rep


Out[53]:
'Represent(x=1, y="Rustom")'

In [8]:
# sets: mutable unordered collection of unique objects

In [9]:
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}

In [10]:
print(basket)


set(['orange', 'pear', 'banana', 'apple'])

In [11]:
a = set('abrakadabra')

In [12]:
a


Out[12]:
{'a', 'b', 'd', 'k', 'r'}

In [13]:
a.add('z')

In [14]:
a


Out[14]:
{'a', 'b', 'd', 'k', 'r', 'z'}

In [15]:
# frozen sets: non-mutable sets

In [16]:
b = frozenset('dbdfhbsdjfjsbd')

In [17]:
print(b)


frozenset(['b', 'd', 'f', 'h', 'j', 's'])

In [18]:
b


Out[18]:
frozenset({'b', 'd', 'f', 'h', 'j', 's'})

In [35]:
cities = frozenset({"calcutta", 'delhi', 'bangalore', 'delhi'})

In [36]:
cities


Out[36]:
frozenset({'bangalore', 'calcutta', 'delhi'})

In [21]:
# number data types:

In [31]:
int_num = 10
print(int_num, type(int_num))


(10, <type 'int'>)

In [32]:
float_num = 10.2
print(float_num, type(float_num))


(10.2, <type 'float'>)

In [33]:
complex_num = 2+3.14j
print(complex_num, type(complex_num))


((2+3.14j), <type 'complex'>)

In [34]:
long_num = 123456L
print(long_num, type(long_num))


(123456L, <type 'long'>)

In [37]:
# operations on sets

In [39]:
a = {1,2,3,4,5}
b = {3,4,5,6}

# intersection
print(a.intersection(b))
print(a & b)

#union
print(a.union(b))
print(a | b)

# difference
print(a.difference(b))
print(a - b)

# symmetric difference
print(a.symmetric_difference(b))
print(a ^ b)

# superset check
print(a.issuperset(b))
print(a >= b)

# subset check
print(a.issubset(b))
print(a <= b)

# disjoint  check
print(a.isdisjoint(b))


set([3, 4, 5])
set([3, 4, 5])
set([1, 2, 3, 4, 5, 6])
set([1, 2, 3, 4, 5, 6])
set([1, 2])
set([1, 2])
set([1, 2, 6])
set([1, 2, 6])
False
False
False
False
False

In [40]:
2 in {1,2,3,4}


Out[40]:
True

In [41]:
4 not in {1,2,34,5}


Out[41]:
True

In [42]:
a.add(12545)

In [43]:
a


Out[43]:
{1, 2, 3, 4, 5, 12545}

In [44]:
a.remove(1)

In [45]:
a


Out[45]:
{2, 3, 4, 5, 12545}

In [46]:
a.discard(1)

In [47]:
a


Out[47]:
{2, 3, 4, 5, 12545}

In [48]:
b


Out[48]:
{3, 4, 5, 6}

In [49]:
a.difference(b)


Out[49]:
{2, 12545}

In [50]:
a.symmetric_difference(b)


Out[50]:
{2, 6, 12545}

In [53]:
restaurants = ['Swiggy', 'Aaha Andhra', 'Sri Sagar', 'Swiggy', 'Swiggy', 'Sri Sagar']
print(restaurants)

print('Unique restaurants as set(): ', set(restaurants))
print('Unique restaurants as list()', list(set(restaurants)))


['Swiggy', 'Aaha Andhra', 'Sri Sagar', 'Swiggy', 'Swiggy', 'Sri Sagar']
('Unique restaurants as set(): ', set(['Swiggy', 'Aaha Andhra', 'Sri Sagar']))
('Unique restaurants as list()', ['Swiggy', 'Aaha Andhra', 'Sri Sagar'])

In [54]:
set(restaurants)


Out[54]:
{'Aaha Andhra', 'Sri Sagar', 'Swiggy'}

In [56]:
list(set(restaurants))


Out[56]:
['Swiggy', 'Aaha Andhra', 'Sri Sagar']

In [57]:
unique_restro = set(restaurants)

In [58]:
unique_restro


Out[58]:
{'Aaha Andhra', 'Sri Sagar', 'Swiggy'}

In [59]:
list(unique_restro)


Out[59]:
['Swiggy', 'Aaha Andhra', 'Sri Sagar']

In [60]:
{{1,2}, {3,4}}


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-60-c5fc32a1a2cf> in <module>()
----> 1 {{1,2}, {3,4}}

TypeError: unhashable type: 'set'

In [62]:
x=1
y=2

In [63]:
{x,y}


Out[63]:
{1, 2}

In [64]:
x=5

In [65]:
{x,y}


Out[65]:
{2, 5}

In [66]:
{x,y}


Out[66]:
{2, 5}

In [67]:
x
y


Out[67]:
2

In [68]:
x


Out[68]:
5

In [69]:
y


Out[69]:
2

In [70]:
a


Out[70]:
{2, 3, 4, 5, 12545}

In [71]:
b


Out[71]:
{3, 4, 5, 6}

In [72]:
a - b


Out[72]:
{2, 12545}

In [73]:
b - a


Out[73]:
{6}

In [74]:
a.symmetric_difference(b)


Out[74]:
{2, 6, 12545}

In [75]:
b.symmetric_difference(a)


Out[75]:
{2, 6, 12545}

In [76]:
from collections import Counter

In [77]:
counterA = Counter(['a','b','a','b','c'])

In [78]:
counterA


Out[78]:
Counter({'a': 2, 'b': 2, 'c': 1})

In [1]:
squares = [x*x for x in (1,2,3,4,5,6)]
print(squares)


[1, 4, 9, 16, 25, 36]

In [2]:
[s.upper() for s in "Rustom Potter"]


Out[2]:
['R', 'U', 'S', 'T', 'O', 'M', ' ', 'P', 'O', 'T', 'T', 'E', 'R']

In [9]:
[w.strip(',') for w in ['nsd,,,',',,,fjg','nsdj,fb,jb,df',',,bjdfb,,,hbsd','ndj,,,fbsj,,,']]


Out[9]:
['nsd', 'fjg', 'nsdj,fb,jb,df', 'bjdfb,,,hbsd', 'ndj,,,fbsj']

In [13]:
sentence = "Beautiful is better than ugly"
["".join(sorted(word, key = lambda x: x.lower())) for word in sentence.split()]


  File "<ipython-input-13-8f16b0237a15>", line 2
    ["".join(sorted(word, key = lambda 2*x: x.lower())) for word in sentence.split()]
                                       ^
SyntaxError: invalid syntax

In [14]:
[x for x in 'apple' if x in 'aeiou']


Out[14]:
['a', 'e']

In [15]:
[x for x in 'apple' if x in 'aeiou' else '*']


  File "<ipython-input-15-0abd031b365d>", line 1
    [x for x in 'apple' if x in 'aeiou' else '*']
                                           ^
SyntaxError: invalid syntax

In [16]:
[x if x in 'aeiou' else '*' for x in 'apple']


Out[16]:
['a', '*', '*', '*', 'e']

In [1]:
'spam'


Out[1]:
'spam'

In [2]:
2**100


Out[2]:
1267650600228229401496703205376L

In [3]:
len(str(2**100000))


Out[3]:
30103

In [4]:
3.1415**2


Out[4]:
9.86902225

In [5]:
3.1415*2


Out[5]:
6.283

In [6]:
print(3.1415*2)


6.283

In [7]:
import math
print(math.pi)
print(math.sqrt(89))


3.14159265359
9.43398113206

In [9]:
import random
print(random.random())
print(random.choice([1,2,3,4,43]))


0.892455215521
3

In [13]:
S = 'rustomPotter'

In [14]:
L = list(S)

In [15]:
L


Out[15]:
['r', 'u', 's', 't', 'o', 'm', 'P', 'o', 't', 't', 'e', 'r']

In [16]:
L[1] = '217'

In [17]:
L


Out[17]:
['r', '217', 's', 't', 'o', 'm', 'P', 'o', 't', 't', 'e', 'r']

In [18]:
''.join(L)


Out[18]:
'r217stomPotter'

In [19]:
B = bytearray('rustomPotter')

In [20]:
B


Out[20]:
bytearray(b'rustomPotter')

In [21]:
B.extend('217')

In [22]:
B


Out[22]:
bytearray(b'rustomPotter217')

In [23]:
B.capitalize()


Out[23]:
bytearray(b'Rustompotter217')

In [24]:
B.decode()


Out[24]:
u'rustomPotter217'

In [34]:
B2 = bytearray('roadster')
B2


Out[34]:
bytearray(b'roadster')

In [35]:
B2.append('T')

In [36]:
B2


Out[36]:
bytearray(b'roadsterT')

In [37]:
B2.extend('esla')

In [38]:
B2


Out[38]:
bytearray(b'roadsterTesla')

In [39]:
B2.decode()


Out[39]:
u'roadsterTesla'

In [1]:
'%s, spam and %s' % ('spam', 'SPAM!')


Out[1]:
'spam, spam and SPAM!'

In [4]:
'{0}, eggs and {1}'.format('spam', 'SPAM!')


Out[4]:
'spam, eggs and SPAM!'

In [5]:
'{1}, eggs and {0}'.format('spam', 'SPAM!')


Out[5]:
'SPAM!, eggs and spam'

In [6]:
'{}, eggs and {}'.format('spam', 'SPAM!!!!')


Out[6]:
'spam, eggs and SPAM!!!!'

In [7]:
'{:,.2f}'.format(125646546.4154541)


Out[7]:
'125,646,546.42'

In [12]:
'%.2f and %+05d' % (4561.1545, -54)


Out[12]:
'4561.15 and -0054'

In [ ]:
dir()

In [9]:
while True:
        reply = input("Enter:")
        if reply == "stop": break
        print(int(reply)**2)


3136
2916

In [10]:
range(3)


Out[10]:
[0, 1, 2]

In [11]:
list(range(3))


Out[11]:
[0, 1, 2]

In [12]:
a, *b = range(100)


  File "<ipython-input-12-8656ddfe4090>", line 1
    a, *b = range(100)
       ^
SyntaxError: invalid syntax

In [13]:
type(2>3)


Out[13]:
bool

In [14]:
True


Out[14]:
True

In [4]:
a=0
b=10
while a<b:
    print(a)
    a += 1


0
1
2
3
4
5
6
7
8
9

In [5]:
x = ...


  File "<ipython-input-5-d3de24265832>", line 1
    x = ...
        ^
SyntaxError: invalid syntax

In [11]:
list(range(-5, -15, -1))


Out[11]:
[-5, -6, -7, -8, -9, -10, -11, -12, -13, -14]

In [12]:
s = "abcdefghijklmnopqrstuvwxyz"

In [16]:
for i in xrange(0, len(s), 2): 
    print s[i]


a
c
e
g
i
k
m
o
q
s
u
w
y

In [15]:
for i in s[::2]:
    print i


a
c
e
g
i
k
m
o
q
s
u
w
y

In [17]:
L1 = [1,2,3,4,5,6]
L2 = [7,8,9,10,11,12]

for (x,y) in zip(L1, L2):
    print x,y,'--', x+y


1 7 -- 8
2 8 -- 10
3 9 -- 12
4 10 -- 14
5 11 -- 16
6 12 -- 18

In [18]:
map(ord, 'spam')


Out[18]:
[115, 112, 97, 109]

In [19]:
ord


Out[19]:
<function ord>

In [1]:
f = open('pythonNotes.py')
f.next()


Out[1]:
'# ways of closing the python shell\n'

In [2]:
f.next()


Out[2]:
'\t# closes the python shell and put back the usual terminal\n'

In [5]:
next(f)


Out[5]:
'\t\texit()\n'

In [11]:
for line in open('tensorflow1.py'):
    print line,


# This tutorial is analogous to theano1.py
# It introduces basic variables and functions
# and shows how you can optimize a function.
# I compare this to theano1.py multiple times.
# So you might want to check that out first.

# For the class Data Science: Practical Deep Learning Concepts in Theano and TensorFlow
# https://deeplearningcourses.com/c/data-science-deep-learning-in-theano-tensorflow
# https://www.udemy.com/data-science-deep-learning-in-theano-tensorflow
from __future__ import print_function, division
from builtins import range
# Note: you may need to update your version of future
# sudo pip install -U future

import numpy as np
import tensorflow as tf


# you have to specify the type
A = tf.placeholder(tf.float32, shape=(5, 5), name='A')


# but shape and name are optional
v = tf.placeholder(tf.float32)


# I think this name is more appropriate than 'dot'
w = tf.matmul(A, v)


# similar to Theano, you need to "feed" the variables values.
# In TensorFlow you do the "actual work" in a "session".

with tf.Session() as session:
    # the values are fed in via the appropriately named argument "feed_dict"
    # v needs to be of shape=(5, 1) not just shape=(5,)
    # it's more like "real" matrix multiplication
    output = session.run(w, feed_dict={A: np.random.randn(5, 5), v: np.random.randn(5, 1)})

    # what's this output that is returned by the session? let's print it
    print(output, type(output))

    # luckily, the output type is just a numpy array. back to safety!


# TensorFlow variables are like Theano shared variables.
# But Theano variables are like TensorFlow placeholders.
# Are you confused yet?

# A tf variable can be initialized with a numpy array or a tf array
# or more correctly, anything that can be turned into a tf tensor
shape = (2, 2)
x = tf.Variable(tf.random_normal(shape))
# x = tf.Variable(np.random.randn(2, 2))
t = tf.Variable(0) # a scalar

# you need to "initialize" the variables first
init = tf.global_variables_initializer()

with tf.Session() as session:
    out = session.run(init) # and then "run" the init operation
    print(out) # it's just None

    # eval() in tf is like get_value() in Theano
    print(x.eval()) # the initial value of x
    print(t.eval())


# let's now try to find the minimum of a simple cost function like we did in Theano
u = tf.Variable(20.0)
cost = u*u + u + 1.0

# One difference between Theano and TensorFlow is that you don't write the updates
# yourself in TensorFlow. You choose an optimizer that implements the algorithm you want.
# 0.3 is the learning rate. Documentation lists the params.
train_op = tf.train.GradientDescentOptimizer(0.3).minimize(cost)

# let's run a session again
init = tf.global_variables_initializer()
with tf.Session() as session:
    session.run(init)

    # Strangely, while the weight update is automated, the loop itself is not.
    # So we'll just call train_op until convergence.
    # This is useful for us anyway since we want to track the cost function.
    for i in range(12):
        session.run(train_op)
        print("i = %d, cost = %.3f, u = %.3f" % (i, cost.eval(), u.eval()))


In [12]:
import sys
print sys.path


['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/potter217/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/local/lib/python2.7/dist-packages/IPython/extensions', '/home/potter217/.ipython']

In [13]:
L = [1,2,3,4,5]

In [15]:
I = iter(L)

In [16]:
I


Out[16]:
<listiterator at 0x7f6d3c5781d0>

In [17]:
I.next()


Out[17]:
1

In [1]:
M = map(lambda x:x**2, range(7))
print M


[0, 1, 4, 9, 16, 25, 36]

In [2]:
print M


[0, 1, 4, 9, 16, 25, 36]

In [4]:
for i in M:
    print i

for i in M:
    print i


0
1
4
9
16
25
36
0
1
4
9
16
25
36

In [5]:
for i in M:
    print i


0
1
4
9
16
25
36

In [6]:
xrange(5)


Out[6]:
xrange(5)

In [7]:
range(5)


Out[7]:
[0, 1, 2, 3, 4]

In [9]:
m_iterXrange = iter(xrange(5))

In [10]:
next(m_iterXrange)


Out[10]:
0

In [11]:
next(m_iterXrange)


Out[11]:
1

In [12]:
m_iterXrange.next()


Out[12]:
2

In [15]:
help(int)


Help on class int in module __builtin__:

class int(object)
 |  int(x=0) -> int or long
 |  int(x, base=10) -> int or long
 |  
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is floating point, the conversion truncates towards zero.
 |  If x is outside the integer range, the function returns a long instead.
 |  
 |  If x is not a number or if base is given, then x must be a string or
 |  Unicode object representing an integer literal in the given base.  The
 |  literal can be preceded by '+' or '-' and be surrounded by whitespace.
 |  The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
 |  interpret the base from the string as an integer literal.
 |  >>> int('0b100', base=0)
 |  4
 |  
 |  Methods defined here:
 |  
 |  __abs__(...)
 |      x.__abs__() <==> abs(x)
 |  
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |  
 |  __and__(...)
 |      x.__and__(y) <==> x&y
 |  
 |  __cmp__(...)
 |      x.__cmp__(y) <==> cmp(x,y)
 |  
 |  __coerce__(...)
 |      x.__coerce__(y) <==> coerce(x, y)
 |  
 |  __div__(...)
 |      x.__div__(y) <==> x/y
 |  
 |  __divmod__(...)
 |      x.__divmod__(y) <==> divmod(x, y)
 |  
 |  __float__(...)
 |      x.__float__() <==> float(x)
 |  
 |  __floordiv__(...)
 |      x.__floordiv__(y) <==> x//y
 |  
 |  __format__(...)
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __getnewargs__(...)
 |  
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
 |  
 |  __hex__(...)
 |      x.__hex__() <==> hex(x)
 |  
 |  __index__(...)
 |      x[y:z] <==> x[y.__index__():z.__index__()]
 |  
 |  __int__(...)
 |      x.__int__() <==> int(x)
 |  
 |  __invert__(...)
 |      x.__invert__() <==> ~x
 |  
 |  __long__(...)
 |      x.__long__() <==> long(x)
 |  
 |  __lshift__(...)
 |      x.__lshift__(y) <==> x<<y
 |  
 |  __mod__(...)
 |      x.__mod__(y) <==> x%y
 |  
 |  __mul__(...)
 |      x.__mul__(y) <==> x*y
 |  
 |  __neg__(...)
 |      x.__neg__() <==> -x
 |  
 |  __nonzero__(...)
 |      x.__nonzero__() <==> x != 0
 |  
 |  __oct__(...)
 |      x.__oct__() <==> oct(x)
 |  
 |  __or__(...)
 |      x.__or__(y) <==> x|y
 |  
 |  __pos__(...)
 |      x.__pos__() <==> +x
 |  
 |  __pow__(...)
 |      x.__pow__(y[, z]) <==> pow(x, y[, z])
 |  
 |  __radd__(...)
 |      x.__radd__(y) <==> y+x
 |  
 |  __rand__(...)
 |      x.__rand__(y) <==> y&x
 |  
 |  __rdiv__(...)
 |      x.__rdiv__(y) <==> y/x
 |  
 |  __rdivmod__(...)
 |      x.__rdivmod__(y) <==> divmod(y, x)
 |  
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |  
 |  __rfloordiv__(...)
 |      x.__rfloordiv__(y) <==> y//x
 |  
 |  __rlshift__(...)
 |      x.__rlshift__(y) <==> y<<x
 |  
 |  __rmod__(...)
 |      x.__rmod__(y) <==> y%x
 |  
 |  __rmul__(...)
 |      x.__rmul__(y) <==> y*x
 |  
 |  __ror__(...)
 |      x.__ror__(y) <==> y|x
 |  
 |  __rpow__(...)
 |      y.__rpow__(x[, z]) <==> pow(x, y[, z])
 |  
 |  __rrshift__(...)
 |      x.__rrshift__(y) <==> y>>x
 |  
 |  __rshift__(...)
 |      x.__rshift__(y) <==> x>>y
 |  
 |  __rsub__(...)
 |      x.__rsub__(y) <==> y-x
 |  
 |  __rtruediv__(...)
 |      x.__rtruediv__(y) <==> y/x
 |  
 |  __rxor__(...)
 |      x.__rxor__(y) <==> y^x
 |  
 |  __str__(...)
 |      x.__str__() <==> str(x)
 |  
 |  __sub__(...)
 |      x.__sub__(y) <==> x-y
 |  
 |  __truediv__(...)
 |      x.__truediv__(y) <==> x/y
 |  
 |  __trunc__(...)
 |      Truncating an Integral returns itself.
 |  
 |  __xor__(...)
 |      x.__xor__(y) <==> x^y
 |  
 |  bit_length(...)
 |      int.bit_length() -> int
 |      
 |      Number of bits necessary to represent self in binary.
 |      >>> bin(37)
 |      '0b100101'
 |      >>> (37).bit_length()
 |      6
 |  
 |  conjugate(...)
 |      Returns self, the complex conjugate of any int.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  denominator
 |      the denominator of a rational number in lowest terms
 |  
 |  imag
 |      the imaginary part of a complex number
 |  
 |  numerator
 |      the numerator of a rational number in lowest terms
 |  
 |  real
 |      the real part of a complex number
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T


In [16]:
help("")




In [17]:
help()


Welcome to Python 2.7!  This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/2.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics".  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".


Help on class str in module __builtin__:

class str(basestring)
 |  str(object='') -> string
 |  
 |  Return a nice string representation of the object.
 |  If the argument is a string, the return value is the same object.
 |  
 |  Method resolution order:
 |      str
 |      basestring
 |      object
 |  
 |  Methods defined here:
 |  
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |  
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x
 |  
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |  
 |  __format__(...)
 |      S.__format__(format_spec) -> string
 |      
 |      Return a formatted version of S as described by format_spec.
 |  
 |  __ge__(...)
 |      x.__ge__(y) <==> x>=y
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __getnewargs__(...)
 |  
 |  __getslice__(...)
 |      x.__getslice__(i, j) <==> x[i:j]
 |      
 |      Use of negative indices is not supported.
 |  
 |  __gt__(...)
 |      x.__gt__(y) <==> x>y
 |  
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
 |  
 |  __le__(...)
 |      x.__le__(y) <==> x<=y
 |  
 |  __len__(...)
 |      x.__len__() <==> len(x)
 |  
 |  __lt__(...)
 |      x.__lt__(y) <==> x<y
 |  
 |  __mod__(...)
 |      x.__mod__(y) <==> x%y
 |  
 |  __mul__(...)
 |      x.__mul__(n) <==> x*n
 |  
 |  __ne__(...)
 |      x.__ne__(y) <==> x!=y
 |  
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |  
 |  __rmod__(...)
 |      x.__rmod__(y) <==> y%x
 |  
 |  __rmul__(...)
 |      x.__rmul__(n) <==> n*x
 |  
 |  __sizeof__(...)
 |      S.__sizeof__() -> size of S in memory, in bytes
 |  
 |  __str__(...)
 |      x.__str__() <==> str(x)
 |  
 |  capitalize(...)
 |      S.capitalize() -> string
 |      
 |      Return a copy of the string S with only its first character
 |      capitalized.
 |  
 |  center(...)
 |      S.center(width[, fillchar]) -> string
 |      
 |      Return S centered in a string of length width. Padding is
 |      done using the specified fill character (default is a space)
 |  
 |  count(...)
 |      S.count(sub[, start[, end]]) -> int
 |      
 |      Return the number of non-overlapping occurrences of substring sub in
 |      string S[start:end].  Optional arguments start and end are interpreted
 |      as in slice notation.
 |  
 |  decode(...)
 |      S.decode([encoding[,errors]]) -> object
 |      
 |      Decodes S using the codec registered for encoding. encoding defaults
 |      to the default encoding. errors may be given to set a different error
 |      handling scheme. Default is 'strict' meaning that encoding errors raise
 |      a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
 |      as well as any other name registered with codecs.register_error that is
 |      able to handle UnicodeDecodeErrors.
 |  
 |  encode(...)
 |      S.encode([encoding[,errors]]) -> object
 |      
 |      Encodes S using the codec registered for encoding. encoding defaults
 |      to the default encoding. errors may be given to set a different error
 |      handling scheme. Default is 'strict' meaning that encoding errors raise
 |      a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
 |      'xmlcharrefreplace' as well as any other name registered with
 |      codecs.register_error that is able to handle UnicodeEncodeErrors.
 |  
 |  endswith(...)
 |      S.endswith(suffix[, start[, end]]) -> bool
 |      
 |      Return True if S ends with the specified suffix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      suffix can also be a tuple of strings to try.
 |  
 |  expandtabs(...)
 |      S.expandtabs([tabsize]) -> string
 |      
 |      Return a copy of S where all tab characters are expanded using spaces.
 |      If tabsize is not given, a tab size of 8 characters is assumed.
 |  
 |  find(...)
 |      S.find(sub [,start [,end]]) -> int
 |      
 |      Return the lowest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  format(...)
 |      S.format(*args, **kwargs) -> string
 |      
 |      Return a formatted version of S, using substitutions from args and kwargs.
 |      The substitutions are identified by braces ('{' and '}').
 |  
 |  index(...)
 |      S.index(sub [,start [,end]]) -> int
 |      
 |      Like S.find() but raise ValueError when the substring is not found.
 |  
 |  isalnum(...)
 |      S.isalnum() -> bool
 |      
 |      Return True if all characters in S are alphanumeric
 |      and there is at least one character in S, False otherwise.
 |  
 |  isalpha(...)
 |      S.isalpha() -> bool
 |      
 |      Return True if all characters in S are alphabetic
 |      and there is at least one character in S, False otherwise.
 |  
 |  isdigit(...)
 |      S.isdigit() -> bool
 |      
 |      Return True if all characters in S are digits
 |      and there is at least one character in S, False otherwise.
 |  
 |  islower(...)
 |      S.islower() -> bool
 |      
 |      Return True if all cased characters in S are lowercase and there is
 |      at least one cased character in S, False otherwise.
 |  
 |  isspace(...)
 |      S.isspace() -> bool
 |      
 |      Return True if all characters in S are whitespace
 |      and there is at least one character in S, False otherwise.
 |  
 |  istitle(...)
 |      S.istitle() -> bool
 |      
 |      Return True if S is a titlecased string and there is at least one
 |      character in S, i.e. uppercase characters may only follow uncased
 |      characters and lowercase characters only cased ones. Return False
 |      otherwise.
 |  
 |  isupper(...)
 |      S.isupper() -> bool
 |      
 |      Return True if all cased characters in S are uppercase and there is
 |      at least one cased character in S, False otherwise.
 |  
 |  join(...)
 |      S.join(iterable) -> string
 |      
 |      Return a string which is the concatenation of the strings in the
 |      iterable.  The separator between elements is S.
 |  
 |  ljust(...)
 |      S.ljust(width[, fillchar]) -> string
 |      
 |      Return S left-justified in a string of length width. Padding is
 |      done using the specified fill character (default is a space).
 |  
 |  lower(...)
 |      S.lower() -> string
 |      
 |      Return a copy of the string S converted to lowercase.
 |  
 |  lstrip(...)
 |      S.lstrip([chars]) -> string or unicode
 |      
 |      Return a copy of the string S with leading whitespace removed.
 |      If chars is given and not None, remove characters in chars instead.
 |      If chars is unicode, S will be converted to unicode before stripping
 |  
 |  partition(...)
 |      S.partition(sep) -> (head, sep, tail)
 |      
 |      Search for the separator sep in S, and return the part before it,
 |      the separator itself, and the part after it.  If the separator is not
 |      found, return S and two empty strings.
 |  
 |  replace(...)
 |      S.replace(old, new[, count]) -> string
 |      
 |      Return a copy of string S with all occurrences of substring
 |      old replaced by new.  If the optional argument count is
 |      given, only the first count occurrences are replaced.
 |  
 |  rfind(...)
 |      S.rfind(sub [,start [,end]]) -> int
 |      
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  rindex(...)
 |      S.rindex(sub [,start [,end]]) -> int
 |      
 |      Like S.rfind() but raise ValueError when the substring is not found.
 |  
 |  rjust(...)
 |      S.rjust(width[, fillchar]) -> string
 |      
 |      Return S right-justified in a string of length width. Padding is
 |      done using the specified fill character (default is a space)
 |  
 |  rpartition(...)
 |      S.rpartition(sep) -> (head, sep, tail)
 |      
 |      Search for the separator sep in S, starting at the end of S, and return
 |      the part before it, the separator itself, and the part after it.  If the
 |      separator is not found, return two empty strings and S.
 |  
 |  rsplit(...)
 |      S.rsplit([sep [,maxsplit]]) -> list of strings
 |      
 |      Return a list of the words in the string S, using sep as the
 |      delimiter string, starting at the end of the string and working
 |      to the front.  If maxsplit is given, at most maxsplit splits are
 |      done. If sep is not specified or is None, any whitespace string
 |      is a separator.
 |  
 |  rstrip(...)
 |      S.rstrip([chars]) -> string or unicode
 |      
 |      Return a copy of the string S with trailing whitespace removed.
 |      If chars is given and not None, remove characters in chars instead.
 |      If chars is unicode, S will be converted to unicode before stripping
 |  
 |  split(...)
 |      S.split([sep [,maxsplit]]) -> list of strings
 |      
 |      Return a list of the words in the string S, using sep as the
 |      delimiter string.  If maxsplit is given, at most maxsplit
 |      splits are done. If sep is not specified or is None, any
 |      whitespace string is a separator and empty strings are removed
 |      from the result.
 |  
 |  splitlines(...)
 |      S.splitlines(keepends=False) -> list of strings
 |      
 |      Return a list of the lines in S, breaking at line boundaries.
 |      Line breaks are not included in the resulting list unless keepends
 |      is given and true.
 |  
 |  startswith(...)
 |      S.startswith(prefix[, start[, end]]) -> bool
 |      
 |      Return True if S starts with the specified prefix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      prefix can also be a tuple of strings to try.
 |  
 |  strip(...)
 |      S.strip([chars]) -> string or unicode
 |      
 |      Return a copy of the string S with leading and trailing
 |      whitespace removed.
 |      If chars is given and not None, remove characters in chars instead.
 |      If chars is unicode, S will be converted to unicode before stripping
 |  
 |  swapcase(...)
 |      S.swapcase() -> string
 |      
 |      Return a copy of the string S with uppercase characters
 |      converted to lowercase and vice versa.
 |  
 |  title(...)
 |      S.title() -> string
 |      
 |      Return a titlecased version of S, i.e. words start with uppercase
 |      characters, all remaining cased characters have lowercase.
 |  
 |  translate(...)
 |      S.translate(table [,deletechars]) -> string
 |      
 |      Return a copy of the string S, where all characters occurring
 |      in the optional argument deletechars are removed, and the
 |      remaining characters have been mapped through the given
 |      translation table, which must be a string of length 256 or None.
 |      If the table argument is None, no translation is applied and
 |      the operation simply removes the characters in deletechars.
 |  
 |  upper(...)
 |      S.upper() -> string
 |      
 |      Return a copy of the string S converted to uppercase.
 |  
 |  zfill(...)
 |      S.zfill(width) -> string
 |      
 |      Pad a numeric string S with zeros on the left, to fill a field
 |      of the specified width.  The string S is never truncated.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T

Help on built-in module sys:

NAME
    sys

FILE
    (built-in)

MODULE DOCS
    http://docs.python.org/library/sys

DESCRIPTION
    This module provides access to some objects used or maintained by the
    interpreter and to functions that interact strongly with the interpreter.
    
    Dynamic objects:
    
    argv -- command line arguments; argv[0] is the script pathname if known
    path -- module search path; path[0] is the script directory, else ''
    modules -- dictionary of loaded modules
    
    displayhook -- called to show results in an interactive session
    excepthook -- called to handle any uncaught exception other than SystemExit
      To customize printing in an interactive session or to install a custom
      top-level exception handler, assign other functions to replace these.
    
    exitfunc -- if sys.exitfunc exists, this routine is called when Python exits
      Assigning to sys.exitfunc is deprecated; use the atexit module instead.
    
    stdin -- standard input file object; used by raw_input() and input()
    stdout -- standard output file object; used by the print statement
    stderr -- standard error object; used for error messages
      By assigning other file objects (or objects that behave like files)
      to these, it is possible to redirect all of the interpreter's I/O.
    
    last_type -- type of last uncaught exception
    last_value -- value of last uncaught exception
    last_traceback -- traceback of last uncaught exception
      These three are only available in an interactive session after a
      traceback has been printed.
    
    exc_type -- type of exception currently being handled
    exc_value -- value of exception currently being handled
    exc_traceback -- traceback of exception currently being handled
      The function exc_info() should be used instead of these three,
      because it is thread-safe.
    
    Static objects:
    
    float_info -- a dict with information about the float inplementation.
    long_info -- a struct sequence with information about the long implementation.
    maxint -- the largest supported integer (the smallest is -maxint-1)
    maxsize -- the largest supported length of containers.
    maxunicode -- the largest supported character
    builtin_module_names -- tuple of module names built into this interpreter
    version -- the version of this interpreter as a string
    version_info -- version information as a named tuple
    hexversion -- version information encoded as a single integer
    copyright -- copyright notice pertaining to this interpreter
    platform -- platform identifier
    executable -- absolute path of the executable binary of the Python interpreter
    prefix -- prefix used to find the Python library
    exec_prefix -- prefix used to find the machine-specific Python library
    float_repr_style -- string indicating the style of repr() output for floats
    __stdin__ -- the original stdin; don't touch!
    __stdout__ -- the original stdout; don't touch!
    __stderr__ -- the original stderr; don't touch!
    __displayhook__ -- the original displayhook; don't touch!
    __excepthook__ -- the original excepthook; don't touch!
    
    Functions:
    
    displayhook() -- print an object to the screen, and save it in __builtin__._
    excepthook() -- print an exception and its traceback to sys.stderr
    exc_info() -- return thread-safe information about the current exception
    exc_clear() -- clear the exception state for the current thread
    exit() -- exit the interpreter by raising SystemExit
    getdlopenflags() -- returns flags to be used for dlopen() calls
    getprofile() -- get the global profiling function
    getrefcount() -- return the reference count for an object (plus one :-)
    getrecursionlimit() -- return the max recursion depth for the interpreter
    getsizeof() -- return the size of an object in bytes
    gettrace() -- get the global debug tracing function
    setcheckinterval() -- control how often the interpreter checks for events
    setdlopenflags() -- set the flags to be used for dlopen() calls
    setprofile() -- set the global profiling function
    setrecursionlimit() -- set the max recursion depth for the interpreter
    settrace() -- set the global debug tracing function

FUNCTIONS
    __displayhook__ = displayhook(...)
        displayhook(object) -> None
        
        Print an object to sys.stdout and also save it in __builtin__._
    
    __excepthook__ = excepthook(...)
        excepthook(exctype, value, traceback) -> None
        
        Handle an exception by displaying it with a traceback on sys.stderr.
    
    call_tracing(...)
        call_tracing(func, args) -> object
        
        Call func(*args), while tracing is enabled.  The tracing state is
        saved, and restored afterwards.  This is intended to be called from
        a debugger from a checkpoint, to recursively debug some other code.
    
    callstats(...)
        callstats() -> tuple of integers
        
        Return a tuple of function call statistics, if CALL_PROFILE was defined
        when Python was built.  Otherwise, return None.
        
        When enabled, this function returns detailed, implementation-specific
        details about the number of function calls executed. The return value is
        a 11-tuple where the entries in the tuple are counts of:
        0. all function calls
        1. calls to PyFunction_Type objects
        2. PyFunction calls that do not create an argument tuple
        3. PyFunction calls that do not create an argument tuple
           and bypass PyEval_EvalCodeEx()
        4. PyMethod calls
        5. PyMethod calls on bound methods
        6. PyType calls
        7. PyCFunction calls
        8. generator calls
        9. All other calls
        10. Number of stack pops performed by call_function()
    
    exc_clear(...)
        exc_clear() -> None
        
        Clear global information on the current exception.  Subsequent calls to
        exc_info() will return (None,None,None) until another exception is raised
        in the current thread or the execution stack returns to a frame where
        another exception is being handled.
    
    exc_info(...)
        exc_info() -> (type, value, traceback)
        
        Return information about the most recent exception caught by an except
        clause in the current stack frame or in an older stack frame.
    
    exit(...)
        exit([status])
        
        Exit the interpreter by raising SystemExit(status).
        If the status is omitted or None, it defaults to zero (i.e., success).
        If the status is an integer, it will be used as the system exit status.
        If it is another kind of object, it will be printed and the system
        exit status will be one (i.e., failure).
    
    getcheckinterval(...)
        getcheckinterval() -> current check interval; see setcheckinterval().
    
    getdefaultencoding(...)
        getdefaultencoding() -> string
        
        Return the current default string encoding used by the Unicode 
        implementation.
    
    getdlopenflags(...)
        getdlopenflags() -> int
        
        Return the current value of the flags that are used for dlopen calls.
        The flag constants are defined in the ctypes and DLFCN modules.
    
    getfilesystemencoding(...)
        getfilesystemencoding() -> string
        
        Return the encoding used to convert Unicode filenames in
        operating system filenames.
    
    getprofile(...)
        getprofile()
        
        Return the profiling function set with sys.setprofile.
        See the profiler chapter in the library manual.
    
    getrecursionlimit(...)
        getrecursionlimit()
        
        Return the current value of the recursion limit, the maximum depth
        of the Python interpreter stack.  This limit prevents infinite
        recursion from causing an overflow of the C stack and crashing Python.
    
    getrefcount(...)
        getrefcount(object) -> integer
        
        Return the reference count of object.  The count returned is generally
        one higher than you might expect, because it includes the (temporary)
        reference as an argument to getrefcount().
    
    getsizeof(...)
        getsizeof(object, default) -> int
        
        Return the size of object in bytes.
    
    gettrace(...)
        gettrace()
        
        Return the global debug tracing function set with sys.settrace.
        See the debugger chapter in the library manual.
    
    setcheckinterval(...)
        setcheckinterval(n)
        
        Tell the Python interpreter to check for asynchronous events every
        n instructions.  This also affects how often thread switches occur.
    
    setdlopenflags(...)
        setdlopenflags(n) -> None
        
        Set the flags used by the interpreter for dlopen calls, such as when the
        interpreter loads extension modules.  Among other things, this will enable
        a lazy resolving of symbols when importing a module, if called as
        sys.setdlopenflags(0).  To share symbols across extension modules, call as
        sys.setdlopenflags(ctypes.RTLD_GLOBAL).  Symbolic names for the flag modules
        can be either found in the ctypes module, or in the DLFCN module. If DLFCN
        is not available, it can be generated from /usr/include/dlfcn.h using the
        h2py script.
    
    setprofile(...)
        setprofile(function)
        
        Set the profiling function.  It will be called on each function call
        and return.  See the profiler chapter in the library manual.
    
    setrecursionlimit(...)
        setrecursionlimit(n)
        
        Set the maximum depth of the Python interpreter stack to n.  This
        limit prevents infinite recursion from causing an overflow of the C
        stack and crashing Python.  The highest possible limit is platform-
        dependent.
    
    settrace(...)
        settrace(function)
        
        Set the global debug tracing function.  It will be called on each
        function call.  See the debugger chapter in the library manual.

DATA
    __stderr__ = <open file '<stderr>', mode 'w'>
    __stdin__ = <open file '<stdin>', mode 'r'>
    __stdout__ = <open file '<stdout>', mode 'w'>
    api_version = 1013
    argv = ['/usr/local/lib/python2.7/dist-packages/ipykernel_launcher.py'...
    builtin_module_names = ('__builtin__', '__main__', '_ast', '_bisect', ...
    byteorder = 'little'
    copyright = 'Copyright (c) 2001-2016 Python Software Foundati...ematis...
    displayhook = <ipykernel.displayhook.ZMQShellDisplayHook object>
    dont_write_bytecode = False
    exc_value = TypeError("<module 'sys' (built-in)> is a built-in module"...
    exec_prefix = '/usr'
    executable = '/usr/bin/python'
    flags = sys.flags(debug=0, py3k_warning=0, division_warn...unicode=0, ...
    float_info = sys.float_info(max=1.7976931348623157e+308, max_...epsilo...
    float_repr_style = 'short'
    hexversion = 34016496
    long_info = sys.long_info(bits_per_digit=30, sizeof_digit=4)
    maxint = 9223372036854775807
    maxsize = 9223372036854775807
    maxunicode = 1114111
    meta_path = [<six._SixMetaPathImporter object>, <pkg_resources.extern....
    modules = {'IPython': <module 'IPython' from '/usr/local/lib/python2.7...
    path = ['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linu...
    path_hooks = [<type 'zipimport.zipimporter'>]
    path_importer_cache = {'': None, '/home/potter217/.ipython': None, '/h...
    platform = 'linux2'
    prefix = '/usr'
    ps1 = 'In : '
    ps2 = '...: '
    ps3 = 'Out: '
    py3kwarning = False
    pydebug = False
    stderr = <ipykernel.iostream.OutStream object>
    stdin = <open file '<stdin>', mode 'r'>
    stdout = <ipykernel.iostream.OutStream object>
    subversion = ('CPython', '', '')
    version = '2.7.12 (default, Dec  4 2017, 14:50:18) \n[GCC 5.4.0 201606...
    version_info = sys.version_info(major=2, minor=7, micro=12, releaselev...
    warnoptions = []


Help on class str in module __builtin__:

class str(basestring)
 |  str(object='') -> string
 |  
 |  Return a nice string representation of the object.
 |  If the argument is a string, the return value is the same object.
 |  
 |  Method resolution order:
 |      str
 |      basestring
 |      object
 |  
 |  Methods defined here:
 |  
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |  
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x
 |  
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |  
 |  __format__(...)
 |      S.__format__(format_spec) -> string
 |      
 |      Return a formatted version of S as described by format_spec.
 |  
 |  __ge__(...)
 |      x.__ge__(y) <==> x>=y
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __getnewargs__(...)
 |  
 |  __getslice__(...)
 |      x.__getslice__(i, j) <==> x[i:j]
 |      
 |      Use of negative indices is not supported.
 |  
 |  __gt__(...)
 |      x.__gt__(y) <==> x>y
 |  
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
 |  
 |  __le__(...)
 |      x.__le__(y) <==> x<=y
 |  
 |  __len__(...)
 |      x.__len__() <==> len(x)
 |  
 |  __lt__(...)
 |      x.__lt__(y) <==> x<y
 |  
 |  __mod__(...)
 |      x.__mod__(y) <==> x%y
 |  
 |  __mul__(...)
 |      x.__mul__(n) <==> x*n
 |  
 |  __ne__(...)
 |      x.__ne__(y) <==> x!=y
 |  
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |  
 |  __rmod__(...)
 |      x.__rmod__(y) <==> y%x
 |  
 |  __rmul__(...)
 |      x.__rmul__(n) <==> n*x
 |  
 |  __sizeof__(...)
 |      S.__sizeof__() -> size of S in memory, in bytes
 |  
 |  __str__(...)
 |      x.__str__() <==> str(x)
 |  
 |  capitalize(...)
 |      S.capitalize() -> string
 |      
 |      Return a copy of the string S with only its first character
 |      capitalized.
 |  
 |  center(...)
 |      S.center(width[, fillchar]) -> string
 |      
 |      Return S centered in a string of length width. Padding is
 |      done using the specified fill character (default is a space)
 |  
 |  count(...)
 |      S.count(sub[, start[, end]]) -> int
 |      
 |      Return the number of non-overlapping occurrences of substring sub in
 |      string S[start:end].  Optional arguments start and end are interpreted
 |      as in slice notation.
 |  
 |  decode(...)
 |      S.decode([encoding[,errors]]) -> object
 |      
 |      Decodes S using the codec registered for encoding. encoding defaults
 |      to the default encoding. errors may be given to set a different error
 |      handling scheme. Default is 'strict' meaning that encoding errors raise
 |      a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
 |      as well as any other name registered with codecs.register_error that is
 |      able to handle UnicodeDecodeErrors.
 |  
 |  encode(...)
 |      S.encode([encoding[,errors]]) -> object
 |      
 |      Encodes S using the codec registered for encoding. encoding defaults
 |      to the default encoding. errors may be given to set a different error
 |      handling scheme. Default is 'strict' meaning that encoding errors raise
 |      a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
 |      'xmlcharrefreplace' as well as any other name registered with
 |      codecs.register_error that is able to handle UnicodeEncodeErrors.
 |  
 |  endswith(...)
 |      S.endswith(suffix[, start[, end]]) -> bool
 |      
 |      Return True if S ends with the specified suffix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      suffix can also be a tuple of strings to try.
 |  
 |  expandtabs(...)
 |      S.expandtabs([tabsize]) -> string
 |      
 |      Return a copy of S where all tab characters are expanded using spaces.
 |      If tabsize is not given, a tab size of 8 characters is assumed.
 |  
 |  find(...)
 |      S.find(sub [,start [,end]]) -> int
 |      
 |      Return the lowest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  format(...)
 |      S.format(*args, **kwargs) -> string
 |      
 |      Return a formatted version of S, using substitutions from args and kwargs.
 |      The substitutions are identified by braces ('{' and '}').
 |  
 |  index(...)
 |      S.index(sub [,start [,end]]) -> int
 |      
 |      Like S.find() but raise ValueError when the substring is not found.
 |  
 |  isalnum(...)
 |      S.isalnum() -> bool
 |      
 |      Return True if all characters in S are alphanumeric
 |      and there is at least one character in S, False otherwise.
 |  
 |  isalpha(...)
 |      S.isalpha() -> bool
 |      
 |      Return True if all characters in S are alphabetic
 |      and there is at least one character in S, False otherwise.
 |  
 |  isdigit(...)
 |      S.isdigit() -> bool
 |      
 |      Return True if all characters in S are digits
 |      and there is at least one character in S, False otherwise.
 |  
 |  islower(...)
 |      S.islower() -> bool
 |      
 |      Return True if all cased characters in S are lowercase and there is
 |      at least one cased character in S, False otherwise.
 |  
 |  isspace(...)
 |      S.isspace() -> bool
 |      
 |      Return True if all characters in S are whitespace
 |      and there is at least one character in S, False otherwise.
 |  
 |  istitle(...)
 |      S.istitle() -> bool
 |      
 |      Return True if S is a titlecased string and there is at least one
 |      character in S, i.e. uppercase characters may only follow uncased
 |      characters and lowercase characters only cased ones. Return False
 |      otherwise.
 |  
 |  isupper(...)
 |      S.isupper() -> bool
 |      
 |      Return True if all cased characters in S are uppercase and there is
 |      at least one cased character in S, False otherwise.
 |  
 |  join(...)
 |      S.join(iterable) -> string
 |      
 |      Return a string which is the concatenation of the strings in the
 |      iterable.  The separator between elements is S.
 |  
 |  ljust(...)
 |      S.ljust(width[, fillchar]) -> string
 |      
 |      Return S left-justified in a string of length width. Padding is
 |      done using the specified fill character (default is a space).
 |  
 |  lower(...)
 |      S.lower() -> string
 |      
 |      Return a copy of the string S converted to lowercase.
 |  
 |  lstrip(...)
 |      S.lstrip([chars]) -> string or unicode
 |      
 |      Return a copy of the string S with leading whitespace removed.
 |      If chars is given and not None, remove characters in chars instead.
 |      If chars is unicode, S will be converted to unicode before stripping
 |  
 |  partition(...)
 |      S.partition(sep) -> (head, sep, tail)
 |      
 |      Search for the separator sep in S, and return the part before it,
 |      the separator itself, and the part after it.  If the separator is not
 |      found, return S and two empty strings.
 |  
 |  replace(...)
 |      S.replace(old, new[, count]) -> string
 |      
 |      Return a copy of string S with all occurrences of substring
 |      old replaced by new.  If the optional argument count is
 |      given, only the first count occurrences are replaced.
 |  
 |  rfind(...)
 |      S.rfind(sub [,start [,end]]) -> int
 |      
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  rindex(...)
 |      S.rindex(sub [,start [,end]]) -> int
 |      
 |      Like S.rfind() but raise ValueError when the substring is not found.
 |  
 |  rjust(...)
 |      S.rjust(width[, fillchar]) -> string
 |      
 |      Return S right-justified in a string of length width. Padding is
 |      done using the specified fill character (default is a space)
 |  
 |  rpartition(...)
 |      S.rpartition(sep) -> (head, sep, tail)
 |      
 |      Search for the separator sep in S, starting at the end of S, and return
 |      the part before it, the separator itself, and the part after it.  If the
 |      separator is not found, return two empty strings and S.
 |  
 |  rsplit(...)
 |      S.rsplit([sep [,maxsplit]]) -> list of strings
 |      
 |      Return a list of the words in the string S, using sep as the
 |      delimiter string, starting at the end of the string and working
 |      to the front.  If maxsplit is given, at most maxsplit splits are
 |      done. If sep is not specified or is None, any whitespace string
 |      is a separator.
 |  
 |  rstrip(...)
 |      S.rstrip([chars]) -> string or unicode
 |      
 |      Return a copy of the string S with trailing whitespace removed.
 |      If chars is given and not None, remove characters in chars instead.
 |      If chars is unicode, S will be converted to unicode before stripping
 |  
 |  split(...)
 |      S.split([sep [,maxsplit]]) -> list of strings
 |      
 |      Return a list of the words in the string S, using sep as the
 |      delimiter string.  If maxsplit is given, at most maxsplit
 |      splits are done. If sep is not specified or is None, any
 |      whitespace string is a separator and empty strings are removed
 |      from the result.
 |  
 |  splitlines(...)
 |      S.splitlines(keepends=False) -> list of strings
 |      
 |      Return a list of the lines in S, breaking at line boundaries.
 |      Line breaks are not included in the resulting list unless keepends
 |      is given and true.
 |  
 |  startswith(...)
 |      S.startswith(prefix[, start[, end]]) -> bool
 |      
 |      Return True if S starts with the specified prefix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      prefix can also be a tuple of strings to try.
 |  
 |  strip(...)
 |      S.strip([chars]) -> string or unicode
 |      
 |      Return a copy of the string S with leading and trailing
 |      whitespace removed.
 |      If chars is given and not None, remove characters in chars instead.
 |      If chars is unicode, S will be converted to unicode before stripping
 |  
 |  swapcase(...)
 |      S.swapcase() -> string
 |      
 |      Return a copy of the string S with uppercase characters
 |      converted to lowercase and vice versa.
 |  
 |  title(...)
 |      S.title() -> string
 |      
 |      Return a titlecased version of S, i.e. words start with uppercase
 |      characters, all remaining cased characters have lowercase.
 |  
 |  translate(...)
 |      S.translate(table [,deletechars]) -> string
 |      
 |      Return a copy of the string S, where all characters occurring
 |      in the optional argument deletechars are removed, and the
 |      remaining characters have been mapped through the given
 |      translation table, which must be a string of length 256 or None.
 |      If the table argument is None, no translation is applied and
 |      the operation simply removes the characters in deletechars.
 |  
 |  upper(...)
 |      S.upper() -> string
 |      
 |      Return a copy of the string S converted to uppercase.
 |  
 |  zfill(...)
 |      S.zfill(width) -> string
 |      
 |      Pad a numeric string S with zeros on the left, to fill a field
 |      of the specified width.  The string S is never truncated.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T


no Python documentation found for '[]'


no Python documentation found for '{}'

Help on class str in module __builtin__:

class str(basestring)
 |  str(object='') -> string
 |  
 |  Return a nice string representation of the object.
 |  If the argument is a string, the return value is the same object.
 |  
 |  Method resolution order:
 |      str
 |      basestring
 |      object
 |  
 |  Methods defined here:
 |  
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |  
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x
 |  
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |  
 |  __format__(...)
 |      S.__format__(format_spec) -> string
 |      
 |      Return a formatted version of S as described by format_spec.
 |  
 |  __ge__(...)
 |      x.__ge__(y) <==> x>=y
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __getnewargs__(...)
 |  
 |  __getslice__(...)
 |      x.__getslice__(i, j) <==> x[i:j]
 |      
 |      Use of negative indices is not supported.
 |  
 |  __gt__(...)
 |      x.__gt__(y) <==> x>y
 |  
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
 |  
 |  __le__(...)
 |      x.__le__(y) <==> x<=y
 |  
 |  __len__(...)
 |      x.__len__() <==> len(x)
 |  
 |  __lt__(...)
 |      x.__lt__(y) <==> x<y
 |  
 |  __mod__(...)
 |      x.__mod__(y) <==> x%y
 |  
 |  __mul__(...)
 |      x.__mul__(n) <==> x*n
 |  
 |  __ne__(...)
 |      x.__ne__(y) <==> x!=y
 |  
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |  
 |  __rmod__(...)
 |      x.__rmod__(y) <==> y%x
 |  
 |  __rmul__(...)
 |      x.__rmul__(n) <==> n*x
 |  
 |  __sizeof__(...)
 |      S.__sizeof__() -> size of S in memory, in bytes
 |  
 |  __str__(...)
 |      x.__str__() <==> str(x)
 |  
 |  capitalize(...)
 |      S.capitalize() -> string
 |      
 |      Return a copy of the string S with only its first character
 |      capitalized.
 |  
 |  center(...)
 |      S.center(width[, fillchar]) -> string
 |      
 |      Return S centered in a string of length width. Padding is
 |      done using the specified fill character (default is a space)
 |  
 |  count(...)
 |      S.count(sub[, start[, end]]) -> int
 |      
 |      Return the number of non-overlapping occurrences of substring sub in
 |      string S[start:end].  Optional arguments start and end are interpreted
 |      as in slice notation.
 |  
 |  decode(...)
 |      S.decode([encoding[,errors]]) -> object
 |      
 |      Decodes S using the codec registered for encoding. encoding defaults
 |      to the default encoding. errors may be given to set a different error
 |      handling scheme. Default is 'strict' meaning that encoding errors raise
 |      a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
 |      as well as any other name registered with codecs.register_error that is
 |      able to handle UnicodeDecodeErrors.
 |  
 |  encode(...)
 |      S.encode([encoding[,errors]]) -> object
 |      
 |      Encodes S using the codec registered for encoding. encoding defaults
 |      to the default encoding. errors may be given to set a different error
 |      handling scheme. Default is 'strict' meaning that encoding errors raise
 |      a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
 |      'xmlcharrefreplace' as well as any other name registered with
 |      codecs.register_error that is able to handle UnicodeEncodeErrors.
 |  
 |  endswith(...)
 |      S.endswith(suffix[, start[, end]]) -> bool
 |      
 |      Return True if S ends with the specified suffix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      suffix can also be a tuple of strings to try.
 |  
 |  expandtabs(...)
 |      S.expandtabs([tabsize]) -> string
 |      
 |      Return a copy of S where all tab characters are expanded using spaces.
 |      If tabsize is not given, a tab size of 8 characters is assumed.
 |  
 |  find(...)
 |      S.find(sub [,start [,end]]) -> int
 |      
 |      Return the lowest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  format(...)
 |      S.format(*args, **kwargs) -> string
 |      
 |      Return a formatted version of S, using substitutions from args and kwargs.
 |      The substitutions are identified by braces ('{' and '}').
 |  
 |  index(...)
 |      S.index(sub [,start [,end]]) -> int
 |      
 |      Like S.find() but raise ValueError when the substring is not found.
 |  
 |  isalnum(...)
 |      S.isalnum() -> bool
 |      
 |      Return True if all characters in S are alphanumeric
 |      and there is at least one character in S, False otherwise.
 |  
 |  isalpha(...)
 |      S.isalpha() -> bool
 |      
 |      Return True if all characters in S are alphabetic
 |      and there is at least one character in S, False otherwise.
 |  
 |  isdigit(...)
 |      S.isdigit() -> bool
 |      
 |      Return True if all characters in S are digits
 |      and there is at least one character in S, False otherwise.
 |  
 |  islower(...)
 |      S.islower() -> bool
 |      
 |      Return True if all cased characters in S are lowercase and there is
 |      at least one cased character in S, False otherwise.
 |  
 |  isspace(...)
 |      S.isspace() -> bool
 |      
 |      Return True if all characters in S are whitespace
 |      and there is at least one character in S, False otherwise.
 |  
 |  istitle(...)
 |      S.istitle() -> bool
 |      
 |      Return True if S is a titlecased string and there is at least one
 |      character in S, i.e. uppercase characters may only follow uncased
 |      characters and lowercase characters only cased ones. Return False
 |      otherwise.
 |  
 |  isupper(...)
 |      S.isupper() -> bool
 |      
 |      Return True if all cased characters in S are uppercase and there is
 |      at least one cased character in S, False otherwise.
 |  
 |  join(...)
 |      S.join(iterable) -> string
 |      
 |      Return a string which is the concatenation of the strings in the
 |      iterable.  The separator between elements is S.
 |  
 |  ljust(...)
 |      S.ljust(width[, fillchar]) -> string
 |      
 |      Return S left-justified in a string of length width. Padding is
 |      done using the specified fill character (default is a space).
 |  
 |  lower(...)
 |      S.lower() -> string
 |      
 |      Return a copy of the string S converted to lowercase.
 |  
 |  lstrip(...)
 |      S.lstrip([chars]) -> string or unicode
 |      
 |      Return a copy of the string S with leading whitespace removed.
 |      If chars is given and not None, remove characters in chars instead.
 |      If chars is unicode, S will be converted to unicode before stripping
 |  
 |  partition(...)
 |      S.partition(sep) -> (head, sep, tail)
 |      
 |      Search for the separator sep in S, and return the part before it,
 |      the separator itself, and the part after it.  If the separator is not
 |      found, return S and two empty strings.
 |  
 |  replace(...)
 |      S.replace(old, new[, count]) -> string
 |      
 |      Return a copy of string S with all occurrences of substring
 |      old replaced by new.  If the optional argument count is
 |      given, only the first count occurrences are replaced.
 |  
 |  rfind(...)
 |      S.rfind(sub [,start [,end]]) -> int
 |      
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  rindex(...)
 |      S.rindex(sub [,start [,end]]) -> int
 |      
 |      Like S.rfind() but raise ValueError when the substring is not found.
 |  
 |  rjust(...)
 |      S.rjust(width[, fillchar]) -> string
 |      
 |      Return S right-justified in a string of length width. Padding is
 |      done using the specified fill character (default is a space)
 |  
 |  rpartition(...)
 |      S.rpartition(sep) -> (head, sep, tail)
 |      
 |      Search for the separator sep in S, starting at the end of S, and return
 |      the part before it, the separator itself, and the part after it.  If the
 |      separator is not found, return two empty strings and S.
 |  
 |  rsplit(...)
 |      S.rsplit([sep [,maxsplit]]) -> list of strings
 |      
 |      Return a list of the words in the string S, using sep as the
 |      delimiter string, starting at the end of the string and working
 |      to the front.  If maxsplit is given, at most maxsplit splits are
 |      done. If sep is not specified or is None, any whitespace string
 |      is a separator.
 |  
 |  rstrip(...)
 |      S.rstrip([chars]) -> string or unicode
 |      
 |      Return a copy of the string S with trailing whitespace removed.
 |      If chars is given and not None, remove characters in chars instead.
 |      If chars is unicode, S will be converted to unicode before stripping
 |  
 |  split(...)
 |      S.split([sep [,maxsplit]]) -> list of strings
 |      
 |      Return a list of the words in the string S, using sep as the
 |      delimiter string.  If maxsplit is given, at most maxsplit
 |      splits are done. If sep is not specified or is None, any
 |      whitespace string is a separator and empty strings are removed
 |      from the result.
 |  
 |  splitlines(...)
 |      S.splitlines(keepends=False) -> list of strings
 |      
 |      Return a list of the lines in S, breaking at line boundaries.
 |      Line breaks are not included in the resulting list unless keepends
 |      is given and true.
 |  
 |  startswith(...)
 |      S.startswith(prefix[, start[, end]]) -> bool
 |      
 |      Return True if S starts with the specified prefix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      prefix can also be a tuple of strings to try.
 |  
 |  strip(...)
 |      S.strip([chars]) -> string or unicode
 |      
 |      Return a copy of the string S with leading and trailing
 |      whitespace removed.
 |      If chars is given and not None, remove characters in chars instead.
 |      If chars is unicode, S will be converted to unicode before stripping
 |  
 |  swapcase(...)
 |      S.swapcase() -> string
 |      
 |      Return a copy of the string S with uppercase characters
 |      converted to lowercase and vice versa.
 |  
 |  title(...)
 |      S.title() -> string
 |      
 |      Return a titlecased version of S, i.e. words start with uppercase
 |      characters, all remaining cased characters have lowercase.
 |  
 |  translate(...)
 |      S.translate(table [,deletechars]) -> string
 |      
 |      Return a copy of the string S, where all characters occurring
 |      in the optional argument deletechars are removed, and the
 |      remaining characters have been mapped through the given
 |      translation table, which must be a string of length 256 or None.
 |      If the table argument is None, no translation is applied and
 |      the operation simply removes the characters in deletechars.
 |  
 |  upper(...)
 |      S.upper() -> string
 |      
 |      Return a copy of the string S converted to uppercase.
 |  
 |  zfill(...)
 |      S.zfill(width) -> string
 |      
 |      Pad a numeric string S with zeros on the left, to fill a field
 |      of the specified width.  The string S is never truncated.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T

Help on class int in module __builtin__:

class int(object)
 |  int(x=0) -> int or long
 |  int(x, base=10) -> int or long
 |  
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is floating point, the conversion truncates towards zero.
 |  If x is outside the integer range, the function returns a long instead.
 |  
 |  If x is not a number or if base is given, then x must be a string or
 |  Unicode object representing an integer literal in the given base.  The
 |  literal can be preceded by '+' or '-' and be surrounded by whitespace.
 |  The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
 |  interpret the base from the string as an integer literal.
 |  >>> int('0b100', base=0)
 |  4
 |  
 |  Methods defined here:
 |  
 |  __abs__(...)
 |      x.__abs__() <==> abs(x)
 |  
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |  
 |  __and__(...)
 |      x.__and__(y) <==> x&y
 |  
 |  __cmp__(...)
 |      x.__cmp__(y) <==> cmp(x,y)
 |  
 |  __coerce__(...)
 |      x.__coerce__(y) <==> coerce(x, y)
 |  
 |  __div__(...)
 |      x.__div__(y) <==> x/y
 |  
 |  __divmod__(...)
 |      x.__divmod__(y) <==> divmod(x, y)
 |  
 |  __float__(...)
 |      x.__float__() <==> float(x)
 |  
 |  __floordiv__(...)
 |      x.__floordiv__(y) <==> x//y
 |  
 |  __format__(...)
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __getnewargs__(...)
 |  
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
 |  
 |  __hex__(...)
 |      x.__hex__() <==> hex(x)
 |  
 |  __index__(...)
 |      x[y:z] <==> x[y.__index__():z.__index__()]
 |  
 |  __int__(...)
 |      x.__int__() <==> int(x)
 |  
 |  __invert__(...)
 |      x.__invert__() <==> ~x
 |  
 |  __long__(...)
 |      x.__long__() <==> long(x)
 |  
 |  __lshift__(...)
 |      x.__lshift__(y) <==> x<<y
 |  
 |  __mod__(...)
 |      x.__mod__(y) <==> x%y
 |  
 |  __mul__(...)
 |      x.__mul__(y) <==> x*y
 |  
 |  __neg__(...)
 |      x.__neg__() <==> -x
 |  
 |  __nonzero__(...)
 |      x.__nonzero__() <==> x != 0
 |  
 |  __oct__(...)
 |      x.__oct__() <==> oct(x)
 |  
 |  __or__(...)
 |      x.__or__(y) <==> x|y
 |  
 |  __pos__(...)
 |      x.__pos__() <==> +x
 |  
 |  __pow__(...)
 |      x.__pow__(y[, z]) <==> pow(x, y[, z])
 |  
 |  __radd__(...)
 |      x.__radd__(y) <==> y+x
 |  
 |  __rand__(...)
 |      x.__rand__(y) <==> y&x
 |  
 |  __rdiv__(...)
 |      x.__rdiv__(y) <==> y/x
 |  
 |  __rdivmod__(...)
 |      x.__rdivmod__(y) <==> divmod(y, x)
 |  
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |  
 |  __rfloordiv__(...)
 |      x.__rfloordiv__(y) <==> y//x
 |  
 |  __rlshift__(...)
 |      x.__rlshift__(y) <==> y<<x
 |  
 |  __rmod__(...)
 |      x.__rmod__(y) <==> y%x
 |  
 |  __rmul__(...)
 |      x.__rmul__(y) <==> y*x
 |  
 |  __ror__(...)
 |      x.__ror__(y) <==> y|x
 |  
 |  __rpow__(...)
 |      y.__rpow__(x[, z]) <==> pow(x, y[, z])
 |  
 |  __rrshift__(...)
 |      x.__rrshift__(y) <==> y>>x
 |  
 |  __rshift__(...)
 |      x.__rshift__(y) <==> x>>y
 |  
 |  __rsub__(...)
 |      x.__rsub__(y) <==> y-x
 |  
 |  __rtruediv__(...)
 |      x.__rtruediv__(y) <==> y/x
 |  
 |  __rxor__(...)
 |      x.__rxor__(y) <==> y^x
 |  
 |  __str__(...)
 |      x.__str__() <==> str(x)
 |  
 |  __sub__(...)
 |      x.__sub__(y) <==> x-y
 |  
 |  __truediv__(...)
 |      x.__truediv__(y) <==> x/y
 |  
 |  __trunc__(...)
 |      Truncating an Integral returns itself.
 |  
 |  __xor__(...)
 |      x.__xor__(y) <==> x^y
 |  
 |  bit_length(...)
 |      int.bit_length() -> int
 |      
 |      Number of bits necessary to represent self in binary.
 |      >>> bin(37)
 |      '0b100101'
 |      >>> (37).bit_length()
 |      6
 |  
 |  conjugate(...)
 |      Returns self, the complex conjugate of any int.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  denominator
 |      the denominator of a rational number in lowest terms
 |  
 |  imag
 |      the imaginary part of a complex number
 |  
 |  numerator
 |      the numerator of a rational number in lowest terms
 |  
 |  real
 |      the real part of a complex number
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T

no Python documentation found for '1'


You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)".  Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.

In [19]:
D={1:11, 2:22, 3:33, 4:44, 5:55}

In [20]:
print D


{1: 11, 2: 22, 3: 33, 4: 44, 5: 55}

In [22]:
for k in D.keys().sort():
    print k


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-189f50f84956> in <module>()
----> 1 for k in D.keys().sort():
      2     print k

TypeError: 'NoneType' object is not iterable

In [ ]: