Tuesday 28 June 2011

Python generators

  Generators is one of the important features of python whereby one can generate a series of values while maintaining the state of the function, consider generators as a function which when invoked will return a value and halts execution at that point till you invoke the next() function to continue its execution.
Generators looks like a conventional function, an important difference is that a generator includes the yield statement. It can be used by the for statement as if it were an iterator.

Here is an complete, but silly example of a generator.
>>> def values():
... yield 9
... yield 13
... yield 22
... yield 26
... yield 32
... return

In this case, we simply yield a fixed sequence of values. After yielding five values, it exits. Here’s how this generator is used by a for statement.
>>> for p in values():
... print p
...
9
13
22
26
32

A generator function returns a value not through return statement, but through an yield statement, in other words, the function yields a value at that point of time (when an yield statement is encountered) until its invoked again whereby it completes another cycle till an yield statement is encountered where it returns another value and so on, it has to be noted that such a function can also be terminated, lets look at a factorial example which I hope would be a simple reference.

def factorial():
    count=1
    fact=1
    while 1:
        yield fact
        count=count+1
        fact=fact*count

if __name__=="__main__":
    print "Factorial program using generators."
    func=factorial()
    print "Factorial of 1 =", func.next()
    print "Factorial of 2 =", func.next()
    print "Factorial of 3 =", func.next()
    print "Factorial of 4 =", func.next()
    print "Factorial of 5 =", func.next()

Output

Factorial program using generators.
Factorial of 1 = 1
Factorial of 2 = 2
Factorial of 3 = 6
Factorial of 4 = 24
Factorial of 5 = 120

Explanation:
As I mentioned earlier, a generator function works like a normal function until it hits an yield statement. where it returns a value (yield fact returns the value of fact at that moment) and halts there, maintaining the state of all the variables and the point where it yielded a value, then using the next() method, one can continue the execution of the function where it continues from where it left for another cycle till its an yield is encountered and so on, in this way we can generate a sequence of values like Fibonacci, factorial, square of numbers and so on.

Another example using for loop.
def factorial(n):
    count=1
    fact=1
    while count<=n:
        yield fact
        count=count+1
        fact=fact*count 
if __name__=="__main__":
    print "Factorial program using generators."
    for i in factorial(5):
        print i

Output
Factorial program using generators.
1
2
6
24
120

Explanation:
The above code is similar to previous example except that the for loop takes care of calling the next() function for five times and every time the generator function yields a value, the for loop body executes, when the generator function terminates, the for loop terminates as well.

Monday 27 June 2011

Python List


The list type is a container, that implements the sequence protocol. List holds the number of objects in a given order and it allows add and remove objects from the sequence. List literals are written with in square brackets [].
To creare a list, put a number of expressions in square brackets.
Syntax:
L = [ ]
L = [expression, .....]
Example:
>>> colors=['red','green','blue','red']
>>> colors
['red', 'green', 'blue', 'red']
>>>
>>> numbers=[45,67,23,87]
>>> numbers
[45, 67, 23, 87]

This construct is known as a “list display”. Python also supports computed lists, called “list comprehensions”. I will discuss about it in later posts.
We can also use the built-in list type object to create list.
L = list() #empty list
Example:
>>> numbers=[45,67,23,87]
>>> numbers
[45, 67, 23, 87]
>>>
>>> num=list(numbers)
>>> num
[45, 67, 23, 87]
>>>
Index values are used to access the elements from the list.
>>> num[1]
67
>>> num[3]
87
Python never creates a new list if you assign a list to a variable. Assignment with an = on lists does not make a copy. Instead, assignment makes the two variables point to the one list in memory.
A = []
b = A # Both will point to the same list.
Example:
>>> a=['alice','bob']
>>> b=a # list 'a' aasign to 'b'
>>> b
['alice', 'bob']
>>> a.remove('alice') # Remove an item from list 'a'
>>> b # Item is also removes from list 'b'
['bob']
This shows that the two variables 'a' and 'b' pointing to the same memory location.
The '+' works to append two lists,
>>> [1,2]+[5,6]
[1, 2, 5, 6] 
Looping over list
The for construct 'for var in list ' is an easy way to look at each element in a list.
>>> names = ['alice','bob']
>>> for name in names :
... print name
...
alice
bob

If you need both the index and the item, use the enumerate function:
>>> for index,name in enumerate(names):
... print index, name
...
0 alice
1 bob

If you need only the index, use range and len:
>>> for index in range(len(names)):
... print index
...
0
1

The list object supports the iterator protocol. To explicitly create an iterator, use the built-in iter function:
>>> i=iter(names)
>>> item=i.next()
>>> item
'alice'
>>> item=i.next()
>>> item
'bob'
If a list contains numbers, the built-in sum function gives you the sum:
>>> num=[34,56,23,80]
>>> total=sum(num)
>>> total
193

If a list contains strings, you can combine the string into a single long string using the join string method:
>>> colors
['red', 'green', 'blue', 'red']
 >>> names=''.join(colors)
>>> names
'redgreenbluered'
Modifying Lists
Index values are used to assign values to list. 
>>> names[1]='tom'  # assign new value to list 'names'
>>> names
['alice', 'tom']
If multiple variables that point to the same list, all variables will be updated at the same time.
>>> names=['alice','bob']
>>> name=names
>>> names.append('tom')
>>> name
['alice', 'bob', 'tom']
>>> names
['alice', 'bob', 'tom']
Here both name and names are updated at the same time.
To create a separate list, you can use slicing or the list function to quickly create a copy:
>>> name=names[:]
>>> name
['alice', 'bob', 'tom']
>>> names.append('Rose')
>>> names
['alice', 'bob', 'tom', 'Rose']
>>> name
['alice', 'bob', 'tom']
Other list functions are:
  • list.append(elem) -- adds a single element to the end of the list.
  • list.insert(index, elem) -- inserts the element at the given index
  • list.extend(list2) adds the elements in list2 to the end of the list.
  • list.index(elem) -- searches for the given element from the start of the list and returns its index.
  • list.remove(elem) -- searches for the first instance of the given element and removes it.
  • list.sort() -- sorts the list in place (does not return it).
  • list.reverse() -- reverses the list in place (does not return it)
  • list.pop(index) -- removes and returns the element at the given index.

Searching List

The in operator can be used to check if an item is present in the list:
>>> if 'alice' in names:
... print 'Name exist'
...
Name exist
To get the index of the first matching item, use index:
>>> i=names.index('tom')
>>> print i
2
The index method does a linear search, and stops at the first matching item. If no matching item is found, it raises a ValueError exception.


Sunday 19 June 2011

Statement and Expression

A statement is a unit of code. Two types of statements are print and assignment. In interactive mode interpreter execute the statement and display the result. In script mode includes sequence of statements.
Operators are special symbols, that represent computations. The values the operator is applied to are called operands.
Operators are + (Addition), - (Subtraction), *(Multiplication), / (Division), and ** (Exponentiation).
>>> a=44
>>> a/45
0
When both the operands are integers , then the result is round downs to zero. If either the operands is a floating point number , then the python perform the floating point division.
>>> a/45.0
0.97777777777777775

An Expression is a combination of values, variables and operators.
>>> x=56
>>> x+4
60
If more than one operator appears in an expression, the order of evaluation depends on the rules pf precedence.
  • Parentheses have the highest precedence. eg. 2 * (3-1) is 4
  • Exponentiation has the next higher precedence. eg. 2**1 + 1 is 3
  • Multiplication and division have the same precedence. eg. 2*3-1 is 5
  • Addition and subtraction have the next precedence. eg. 6+4/2 is 8.  Operators with the same precedence are evaluated from left to right.
Strings are enclosed in single or double quotes. '+' operator used for concatenation.
Example:
>>> a='Hi'
>>> b='Alice'
>>> a+b # '+' is used for concatenation operation.
'HiAlice'
>>>
'*' operator is also work with string.
>>> a*3 # Disply the value of a in 3 times
'HiHiHi'
>>>

Sample exercise
Assume that we execute the following assignment statements:
width = 17
height = 12.0
delimiter = '.'
For each of the following expressions, write the value of the expression
  1. width/2
  2. width/2.0
  3. height/3
  4. 1 + 2 * 5
  5. delimiter * 5
Use the Python interpreter to check your answers
Answer
>>> width=17
>>> height=12.0
>>> delimiter = '.'
>>> width/2
8
>>> width/2.0
8.5
>>> height/3
4.0
>>> 1+2*5
11
>>> delimiter *5
'.....'
>>>

Variables

    Two basic things related to the programs are values and types. Values are like 1, 5, 2.7, and 'Hello'. Here 1 and 5 is an integer (int), 2.7 is a floating point number (float) and 'Hello' is a string (str) .
     Variable is a name that refers to a value. In python type of the variable is not defined when we create a variable. Based on the value of the variable memory is allocated for it.
Assignment statement (=) used to assign values to a variable.
Example:
>>> message = 'Hello'
>>> message
'Hello'
>>> type(message)
<type 'str'>
>>>
Here message is a variable, we assign a value 'Hello' to it. If you are not sure what type a value has, the interpreter can tell you. In this example 'Hello' is a string (str). Based on this value memory is allocated for message.

Another examples are,
>>> a=4.5
>>> type(a)
<type 'float'>
>>> b='Alice'
>>> type(b)
<type 'str'>
>>> c=684
>>> type(c)
<type 'int'>
>>> a
4.5
>>> b
'Alice'
>>> c
684
>>>
We can also use the print statement to display the value of a variable.

>>> a='Bob'
>>> print a
Bob
>>>
We can assign value of one variable in to another variable by using assignment operator.

>>> a=45
>>> b=a
>>> a
45
>>> b
45
>>>
Variable names can contain both letters and numbers. But they have to begin with a letter. The underscore character (_) can appear in a name. It is often used in names with multiple words such as
front_end, back_end. If we given an illegal name, get a syntax error.
Example:

>>> 76message='Hello'                # Begin with integer
SyntaxError: invalid syntax
>>>
>>> class = 23                              # 'class' is an python keyword
SyntaxError: invalid syntax
>>>
>>> begin@ = 3                           # '@' is an illegal character
SyntaxError: invalid syntax
>>>
python has 31 keywords.
and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try
The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names.