Classes in Python

Python is an object-oriented programming language.

#creating class and function
class Time(object):
    """Represents the time of day."""
    def print_time(self):
        print '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)

    def increment(self, seconds):
        self.second += seconds
        if self.second >= 60:
            self.second -= 60
            self.minute += 1
        if self.minute >= 60:
            self.minute -= 60
            self.hour += 1

    def is_after(self, other):
        return self.time_to_int() > other.time_to_int()

    def __init__(self, hour=0, minute=0, second=0):
        self.hour = hour
        self.minute = minute
        self.second = second
>>> start = Time()
>>> start.print_time()
00:00:00
>>> start = Time (9)
>>> time.print_time()
09:00:00
>>> start.hour = 9
>>> start.minute = 45
>>> start.second = 00
>>> start.print_time()
09:45:00
>>> end = start.increment(1337)
>>> end.print_time()
10:07:17

The __str__ Method

# inside class Time
    def __str__(self):
        return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)

>>> time = Time(9, 45)
>>> print time
09:45:00

Operator Overloading

# inside class Time
    def __add__(self, other):
        if isinstance(other, Time):
            return self.add_time(other)
        else:
            return self.increment(other)
    def add_time(self, other):
        seconds = self.time_to_int() + other.time_to_int()
        return int_to_time(seconds)
    def increment(self, seconds):
        seconds += self.time_to_int()
        return int_to_time(seconds)
>>> start = Time(9, 45)
>>> duration = Time(1, 35)
>>> print start + duration
11:20:00
>>> print start + 1337
10:07:17

Polymorphism – Functions that can work with several types are called polymorphic. Sum is Python’s built-in function. Since Time objects provide an add method, they work with sum.

>>> t1 = Time(7, 43)
>>> t2 = Time(7, 41)
>>> t3 = Time(7, 37)
>>> total = sum([t1, t2, t3])
>>> print total
23:01:00

Inheritance – The new class inherits the methods of the existing class. The existing class is called the parent and the new class is called the child.

Advertisements

Tuples in Python

✓ Tuple – A tuple is a sequence of values, and tuple are immutable.

>>> t = 'a', 'b', 'c', 'd', 'e'
>>> t = ('a', 'b', 'c', 'd', 'e')

>>> print tuple('lupins')
('l', 'u', 'p', 'i', 'n', 's')

>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print t[0]
'a'
>>> print t[1:3]
('b', 'c')

✓ Tuples as return values

#Built-in function divmod takes two arguments and returns a tuple of two values
>>> t = divmod(7, 3)
>>> print t
(2, 1)

✓ Variable-length argument – Functions can take a variable number of arguments. A parameter name that begins with * gathers arguments into a tuple.

def printall(*args):
    print args
>>> printall(1, 2.0, '3')
(1, 2.0, '3')

>>> t = (7, 3)
>>> divmod(t)
TypeError: divmod expected 2 arguments, got 1
>>> divmod(*t)
(2, 1)

✓ Lists and Tuples

>>> s = 'abc'
>>> t = [0, 1, 2]
>>> zip(s, t)
[('a', 0), ('b', 1), ('c', 2)]

def has_match(t1, t2):
    for x, y in zip(t1, t2):
        if x == y:
        return True
    return False

✓ Dictionaries and tuples – Dictionaries’ items method is used to create a list of tuples

>>> d = {'a':0, 'b':1, 'c':2}
>>> t = d.items()
>>> print t
[('a', 0), ('c', 2), ('b', 1)]

>>> t = [('a', 0), ('c', 2), ('b', 1)]
>>> d = dict(t)
>>> print d
{'a': 0, 'c': 2, 'b': 1}

>>> d = dict(zip('abc', range(3)))
>>> print d
{'a': 0, 'c': 2, 'b': 1}

Dictionaries in Python

✓ Dictionary – Dictionary is like list but in here indices can be any type. The association of a key and a value is called a key-value pair.

#Creating an empty dictionary
>>> abc = dict()
>>> print abc
{}
#Adding key-value pair to dictionary
>>> abc['one'] = 'uno'
>>> print eng2sp
{'one': 'uno'}

#If key is not available in dictionary
>>> print eng2sp['four'] 
KeyError: 'four'

# Checking key in dict
>>> 'one' in eng2sp 
True
>>> 'uno' in eng2sp
False

# Checking values in dict
>>> vals = eng2sp.values()
>>> 'uno' in vals
True

✶ The order of items in a dictionary is unpredictable.

✓ Counting how many times each letter occured in string

def count(s):
    d = dict()
    for c in s:
        if c not in d:
            d[c] = 1
        else:
            d[c] += 1
    return d

def print_count(h):
    for c in h:
        print c, h[c]

✓ Dictionaries and Lists

#Inverting dictionary
def invert_dict(d):
    inverse = dict()
    for key in d:
       val = d[key]
       if val not in inverse:
           inverse[val] = [key]
       else:
           inverse[val].append(key)
    return inverse

Lists in Python

✓ List – It is a sequence of values. The values in a list are called elements/ items. Lists are mutable.

>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> print cheeses
['Cheddar', 'Edam', 'Gouda']
>>>  = [17, 123]
>>> print numbers
[17, 123] 
>>> empty = []
>>> print empty
[]

>>> print cheeses[0]
Cheddar

>>> numbers = [17, 123]
>>> numbers[1] = 5 #list are mutable
>>> print numbers
[17, 5]

✶ List indices work the same way as string indices.
✶ Any integer expression can be used as an index.
✶ If you try to read or write an element that does not exist, you get an IndexError.
✶ If an index has a negative value, it counts backward from the end of the list.

>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False

for cheese in cheeses:
print cheese

✓ List operations

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> print a+b
[1, 2, 3, 4, 5, 6]

# sorting
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> print t.sort()
['a', 'b', 'c', 'd', 'e']

✓ Map, filter, and reduce operations

>>> t = [1, 2, 3]
>>> sum(t)
6

#Capitalizing all the elements
def capitalize_all(t):
    res = []
    for s in t:
       res.append(s.capitalize())
    return res

#Selecting only capital elements
def only_upper(t):
    res = []
    for s in t:
        if s.isupper():
            res.append(s)
    return res

✓ Deleting elements

>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print t
['a', 'c']
>>> print x
b
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> print t
['a', 'c']
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print t
['a', 'c']
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> print t
['a', 'f']

✓ Lists and strings

#Convert string to list of characters
>>> s = 'spam'
>>> t = list(s)
>>> print t
['s', 'p', 'a', 'm']

#Convert sring to list of words
>>> s = 'pining for the fjords'
>>> t = s.split()
>>> print t
['pining', 'for', 'the', 'fjords']

>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> s.split(delimiter)
['spam', 'spam', 'spam']

>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter = ' '
>>> delimiter.join(t)
'pining for the fjords'

✓ List aliasing

>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True

#If a change made on one alias, that will affect other as well
>>> b[0] = 17
>>> print a
[17, 2, 3]

✓ List as argument

def delete_head(t):
   del t[0]

>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> print letters
['b', 'c']

String operation in Python

✓ A string is a sequence of characters.

>>> fruit = 'banana'
>>> print fruit[1]
a
>>> print fruit[0]
b
>>> print len(fruit)
6
>>> print fruit[length]
IndexError: string index out of range
>>> print fruit[length-1]
a
#Traversal with a for Loop
index = 0
while index < len(fruit):
    letter = fruit[index]
    print letter
    index = index + 1

for char in fruit:
   print char
>>> s = 'Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
Python
>>> fruit = 'banana'
>>> print fruit[:3]
'ban'
>>> print fruit[3:]
'ana'

✓ String searching operation

def find(word, letter):
    index = 0
    while index < len(word):         
        if word[index] == letter:             
            return index         
        index = index + 1     
    return -1 

>>> word = 'banana'
>>> print word.find('a')
1
>>> print word.find('na')
2

✓ in Operator

>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False

Iterations in Python

✓ While loop

def countdown(n):
    while n > 0:
        print n
        n = n-1
#output: 5,4,3,2,1
def sequence(n):
    while n != 1:
        print n,
        if n%2 == 0:
        n = n/2
    else:
        n = n*3+1;

#output: 3, 10, 5, 16, 8, 4, 2, 1

✓ Break – Break statement is used to jump out of the loop.

while True:
   line = raw_input('> ')
   if line == 'done':
       break;
   print line

✓ Square roots – Loops can be also used in programs that compute numerical results by starting with an approximate answer and iteratively improving it. Square root can be estimated using Newton’s method.

✓ Newton’s method:
newton_method

f(xn) = xn2-S
xn+1 = xn – f(xn)/f’(xn)
xn+1 = xn – xn2-S/ 2xn
xn+1 = (xn + S/ xn)/2

>>> a = 4.0 # square root of 4.0 needs to estimated
>>> x = 3.0 # first approximate value is 3.0 
>>> y = (x + a/x) / 2
>>> print y 
2.16666666667 
>>> x = y # second approximate value
>>> y = (x + a/x) / 2
>>> print y
2.00641025641 # third approximate value

# accurate value can esimate by loop
while True:
    print x
    y = (x + a/x) / 2
    if abs(y-x) < epsilon:
        break
    x = y

Estimate 1/d using the newton’s method.
f(xn) = 1/xn – d
f’(xn) = -1/xn2
xn+1 = xn- (1/xn – d )/(-1/xn2)
xn+1 = xn(2-dxn)

Bisection Debugging

Functions in Python (contd)

✓ Return value functions

e = math.exp(1.0)
height = radius * math.sin(radians)

def area(radius):
    area = math.pi * r**2
    return area

def area(r):
    return math.pi * r**2

def absolute_value(y):
    if y < 0:
        return -y
    else:
        return y

✓ Some complex functions

def distance(x1, y1, x2, y2):
    dx = x2 - x1
    dy = y2 - y1
    dsquared = dx**2 + dy**2
    result = math.sqrt(dsquared)
    return result

✓ Composition functions

def circle_area(xc, yc, xp, yp):
    return area(distance(xc, yc, xp, yp))

✓ Boolean Functions – It can return boolean values

def is_divisible(x, y):
    if x % y == 0:
        return True
    else:
        return False

✓ Recursion (contd)

# Factorial series
def factorial(n):
    if n == 0:
        return 1
    else:
        return n*factorial(n-1)

#Fibonacci seies
def fibonacci (n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)

✓ Checking Types – We can use the built-in function isinstance to verify the type of the argument.

def factorial (n):
    if not isinstance(n, int):
        print 'Factorial is only defined for integers.'
        return None
    elif n < 0:
        print 'Factorial is not defined for negative integers.'
        return None
    elif n == 0:
        return 1
    else:
        return n * factorial(n-1)