Abhishek Gupta, Artificial Intelligence Club, DA-IICT
version 0.1, Released 25/1/2014
This work is licensed under a GNU General Public License, version 2
Some supporting reasons:
More:
I prefer to work in linux. I will follow linux way in this tutorial but will also give some directions for win user, if I know any.
Windows:
Just follow this Enthought Canopy. This is one click installation for windows.
Linux (src):
pre-requisite:
sudo apt-get install python-pip python-dev build-essential
Actual Packages:
sudo pip install numpy
sudo apt-get install libatlas-base-dev gfortran
sudo pip install scipy
Optional Packages:
sudo pip install ipython OR sudo apt-get install ipython
sudo apt-get install ipython-notebook
sudo pip install matplotlib OR sudo apt-get install python-matplotlib
sudo pip install -U scikit-learn
sudo pip install pandas
In [13]:
2 + 3
Out[13]:
In [203]:
2 - 3
Out[203]:
In [4]:
4 / 2
Out[4]:
In [7]:
22 / 7.0 #pi
Out[7]:
In [8]:
191 * 7 #What is this??
Out[8]:
In [27]:
2 ** 8
Out[27]:
In [11]:
print type(1), type(1.0), type('a'), type(dir)
In [12]:
dir()
Out[12]:
In [17]:
import math
golden_ratio = (1 + math.sqrt(_13)) / 2
print golden_ratio
In [18]:
x = 1
type(x)
Out[18]:
In [19]:
x = 1.0
type(x)
Out[19]:
In [20]:
x = False
type(x)
Out[20]:
In [22]:
x = 1j
print type(x)
print x.real, x.imag
In [25]:
x = 10.12
print x is float
print int(x)
In [32]:
5 ** 2 + 2 - 1 / 5.0 * 8
Out[32]:
In [35]:
print 4.3 / 4.1, 4.3 // 4.1
In [38]:
True and False
Out[38]:
In [39]:
True or False
Out[39]:
In [40]:
not False
Out[40]:
In [43]:
0b0101 | 0b0011
Out[43]:
In [44]:
0b0101 & 0b0011
Out[44]:
In [45]:
0b0101 ^ 0b0011
Out[45]:
In [49]:
2 > 1, 2 < 1
Out[49]:
In [50]:
2 >= 2, 2 <= 2
Out[50]:
In [51]:
1 == 1
Out[51]:
In [52]:
'Hello, World!', "Hello, World!"
Out[52]:
In [55]:
s = "Hello, World!"
print s
In [56]:
type(s), len(s), s[0]
Out[56]:
In [64]:
s[0:5], s[2:], s[2:-2] #slicing
Out[64]:
In [63]:
s[::3], s[-1::-1]
Out[63]:
In [70]:
s + ' ,' + s + s[-1] * 5
Out[70]:
In [72]:
s + str(42)
Out[72]:
In [75]:
num1 = 42
print 'What is universe? ', num1
In [78]:
num2 = 1.0
print 'Integer %d, Float %f' % (num1,num2),
print '.'
In [92]:
l = [1,2,3,4]
print type(l), len(l), l
In [84]:
days_of_the_week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
print days_of_the_week
In [83]:
hybrid = ["Tuesday", 1, "Thursday", 5.0, "Saturday", l]
print hybrid
In [107]:
l[2], days_of_the_week[::2], hybrid[5][2]
Out[107]:
In [108]:
l.append(5)
l.append(-1)
l.append('numbers')
l.append('')
print l
In [88]:
range(10), range(2,10), range(2,10,2)
Out[88]:
In [97]:
helloList = list(s)
In [109]:
l.sort()
print l
In [114]:
del l[-2:]
print l
In [115]:
point = (10, 20)
print type(point), len(point), point
In [116]:
x = 4,
print x
In [117]:
x,y = point
print x,y
In [118]:
point[0] = 4
In [119]:
params = {"parameter1" : 1.0,
"parameter2" : 2.0,
"parameter3" : 3.0,}
print type(params), len(params), params
In [120]:
params["parameter1"] = "A"
params["parameter2"] = "B"
# add a new entry
params["parameter4"] = "D"
print params
In [122]:
print params.keys(), params.values()
In [124]:
statement1, statement2 = False, False
if statement1:
print("statement1 is True")
elif statement2:
print("statement2 is True")
else:
print("statement1 and statement2 are False")
In [125]:
statement1 = statement2 = True
if statement1:
if statement2:
print("both statement1 and statement2 are True")
In [126]:
for x in [1,2,3]:
print(x)
In [128]:
for x in range(4):
print(x)
In [129]:
for key, value in params.items():
print(key + " = " + str(value))
In [130]:
for x in params:
print(x + " = " + str(params[x]))
In [131]:
for idx, x in enumerate(range(-3,3)):
print(idx, x)
In [132]:
i = 0
while i < 5:
print(i)
i = i + 1
print("done")
In [134]:
lst = [a for a in range(10)]
print lst
In [135]:
squares = [x**2 for x in range(10)]
print squares
In [137]:
evenSquares = [x**2 for x in range(10) if x%2 == 0]
print evenSquares
In [140]:
combos = []
for x in [1,2,3]:
for y in [3,1,4]:
if x != y:
combos.append((x,y))
print combos
combosLCWay = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
print combosLCWay
In [146]:
mat = [[1,2],[3,4]]
nestedLC = [y for x in mat for y in x]
print nestedLC
#nestedLC Equivalent
nestedLCEq = []
for x in mat:
for y in x:
nestedLCEq.append(y)
print nestedLCEq
In [147]:
mat = [(1,2),[3,4]]
d = {key: value for (key, value) in mat}
print d
In [149]:
def func0():
print("test")
func0()
In [150]:
def func1(arg1, arg2=2, *args, **kwargs):
"""
Print a string 's' and tell how many characters it has
"""
print arg1, arg2, args, kwargs
In [151]:
func1('Hello')
In [152]:
func1('Hello', 5)
In [153]:
func1('Hello', 5, 8, 'Bye')
In [154]:
func1('Hello', 5, 8, 'Bye', name='John', age='15')
In [156]:
func1('Hello', 5, 8, 'Bye', name='John', age='15', 88)
A class is a structure for representing an object and the operations that can be performed on the object. In Python a class can contain attributes (variables) and methods (functions).
Each class method should have an argument self as it first argument. This object is a self-reference. Some class method names have special meaning, for example:
For more: Special method names
In [157]:
class Point:
"""
Simple class for representing a point in a Cartesian coordinate system.
"""
def __init__(self, x, y):
"""
Create a new Point at x, y.
"""
self.x = x
self.y = y
def translate(self, dx, dy):
"""
Translate the point by dx and dy in the x and y direction.
"""
self.x += dx
self.y += dy
def __str__(self):
return("Point at [%f, %f]" % (self.x, self.y))
To create a new instance of a class:
In [158]:
p1 = Point(0, 0) # this will invoke the __init__ method in the Point class
print(p1) # this will invode the __str__ method
To invoke a class method in the class instance p:
In [159]:
p2 = Point(1, 1)
p1.translate(0.25, 1.5)
print(p1)
print(p2)
Python iterator objects required to support two methods while following the iterator protocol.
In [163]:
class Counter(object):
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
'Returns itself as an iterator object'
return self
def next(self):
'Returns the next value till current is lower than high'
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
c = Counter(5,10)
for i in c:
print i,
In [165]:
#Code behind previous iteration
iterator = iter(c)
while True:
try:
x = iterator.next()
print x,
except StopIteration as e:
break
In [166]:
def my_generator():
print "Inside my generator"
yield 'a'
yield 'b'
yield 'c'
In [168]:
print my_generator()
In [170]:
for char in my_generator():
print char
print 'Hi'
In [171]:
def counter_generator(low, high):
while low <= high:
yield low
low += 1
for i in counter_generator(5,10):
print i,
Generator are not re-usable:
In [173]:
g = my_generator()
for c in g:
print c
print 'Second call'
for c in g:
print c
One way to create a reusable generator is Object based generators which does not hold any state. Any class with a __iter__ method which yields data can be used as a object generator.
In [177]:
class Counter(object):
def __init__(self, low, high):
self.low = low
self.high = high
def __iter__(self):
counter = self.low
while self.high >= counter:
yield counter
counter += 1
gobj = Counter(5, 10)
for num in gobj:
print num,
print '\n\nSecond Call:\n'
for num in gobj:
print num,
In [181]:
def sqr(x):return x**2
lSquare = map(sqr, l)
print l, lSquare
In [183]:
l1 = [1,2,3,4]
l2 = [6,7,8,5]
points = zip(l1,l2)
print points
In [185]:
#Reverse Zipping
l1_new, l2_new = zip(*points)
print l1_new, l2_new
In [199]:
zip?
In [201]:
import sys
print sys.version