Thoughts on Programming

July 13, 2011

C bitwise operators – Precedence and associativity

Filed under: C — shadiyya @ 1:48 am

Bitwise means working at the level of single bits. We need to know about the precedences and associativities of different bitwise operators for efficient and error prone coding. An operator’s precedence is meaningful only if other operators with higher or lower precedence are present. Expressions with higher-precedence operators are evaluated first. The grouping of operands can be forced by using parentheses. Where several operators appear together, they have equal precedence and are evaluated according to their associativity. The following table list the C language operators in order of precedence and show the direction of associativity for each operator.





++  —
Parentheses (function call)
Brackets (array subscript)
Postfix increment/decrement


++  —
+  –
!  ~
Prefix increment/decrement
Unary plus/minus
Logical negation/bitwise complement
Cast (change type)
Determine size in bytes
*  /  % Multiplication/division/modulus left-to-right
+  – Addition/subtraction left-to-right
<<  >> Bitwise shift left, Bitwise shift right left-to-right
<  <=
>  >=
Relational less than/less than or equal to
Relational greater than/greater than or equal to
==  != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
+=  -=
*=  /=
%=  &=
^=  |=
<<=  >>=
Addition/subtraction assignment
Multiplication/division assignment
Modulus/bitwise AND assignment
Bitwise exclusive/inclusive OR assignment
Bitwise shift left/right assignment


Comma (separate expressions) left-to-right

July 7, 2011

How to use VIM…

Filed under: Python — shadiyya @ 3:06 am

When we first open the VIM editor, we are in the command mode of the editor. The command mode is where we can type awesome VIM commands to manipulate text.

Insertion mode is just where we can type text normally. To get into insertion mode, press insert key and to get into command mode, press the Esc key.

If you’re ever not sure which mode you’re in, just press the Esc key and you’ll be in command mode for sure.

The following commands are executed in command mode.

Copy & Paste

Press v. (To enter visual mode so you can highlight stuff)
Use the arrow keys (or h,j,k,l,w,b,$) to higlight
Press y to yank, p to paste. (shift-p to open up a line above and paste)

Copy a word      yw
Copy a line     yy
Copy from cursor to end of line     y$


Press v. (To enter visual mode so you can highlight stuff)
Use the arrow keys (or h,j,k,l,w,b,$) to higlight and press d
Delete character     x
Delete word     dw
Delete word and insert text     cw
Delete line     dd
Delete to end of line     D
Delete 2 lines     d2d


Press v and then arrow keys (or h,j,k,l,w,$) to highlight lines of text.
Type > or < to indent right or left.
(if you want to indent more, type 2> or 3>.

Insert Text

Insert at cursor i
Insert after cursor a (useful when at the end of a line)
Open a line below cursor and insert     o
Open a line above cursor and insert     shift-o

Moving Around

Go up     k
Go down     j
Go left     h
Go right     l
Go right a word     w
Go left a word     b
Go to beginning of file     gg
Go to end of file     G
Go to beginning of non-whitespace part of line     ^
Go to end of line     $
Go 22 lines down     22j
Go right 5 words     5w


Type :q to quit the VIM editor.


Type :w to write to the file.

Search & Replace

Search / (after the slash put whatever you want to find and press the enter key)

Find next     n
Find previous     N

Turn off highlighting (after a search)     :noh

Find next instance of a word that your text cursor is over     *

Search from current line to end of file :,$s/search/replace/gc (the gc means global and confirm)

Shell (Exit temporarily to a shell)     :sh

To come back to VIM from the shell type exit

Tab Setting

(to set the tab-size, type :set ts=4 (or whatever number you want)

Undo & Redo

Undo     u
Redo     ctrl-r

View Directory & Files

Type :S
This will split the window and open up a file explorer. Use the enter key to select directories or open files.

June 28, 2011

List comprehensions

Filed under: Python — shadiyya @ 2:38 am

List comprehensions provide a concise way to create lists from existing lists. Each list comprehension consists of an expression followed by a for clause, then zero or more for or if clauses. The result will be a list resulting from evaluating the expression in the context of the for and if clauses which follow it.

>>> a = [x*10 for x in range(8)]

>>> a = [x*9 for x in range(8)]

>>> b = [5*i for i in range(9)]

>>> c = [x for x in a if x % 2 == 0]

>>> print a; print b; print c

[0, 9, 18, 27, 36, 45, 54, 63]

[0, 5, 10, 15, 20, 25, 30, 35, 40]

[0, 18, 36, 54]

Lists can containn any type of elements, including strings, nested lists and functions. The following program works on a list of strings and produces a list of lists.

>>> words = ‘Here is a simple program’.split()

>>> print words

[‘Here’, ‘is’, ‘a’, ‘simple’, ‘program’]

>>> stuff = [[w.upper(), w.lower(), len(w)] for w in words]

>>> for i in stuff:

…          print i

[‘HERE’, ‘here’, 4]

[‘IS’, ‘is’, 2]

[‘A’, ‘a’, 1]

[‘SIMPLE’, ‘simple’, 6]

[‘PROGRAM’, ‘program’, 7]

June 27, 2011

Python: Generators

Filed under: Python — shadiyya @ 5:24 pm

Generators are one of important features of python. A generator is a function that when called executes up to a ‘yield’ command. When we call a generator function, it returns a generator object. This object stores information about the original function and the values of the variables in the function and the location of the code to run next. So next time the function is called, it resume from the point it had stopped and continue execution.

Here is an example:

>>> def test():

print ‘first’

yield 1

print ‘second’

yield 2

To execute the function, we have to use the ‘next()’ method.

>>> place = test()








Traceback (most recent call last):

File “<stdin>” line 1, in ?


We can use for loop in the generator, which works by calling and assigning the obtained value to i.

>>> place = test()

>>> for i in place:

…            print i





Here is a program for printing factorials as an example for generators:

 # A simple factorial program using python generators with iterations

>>>  def factorial(n):

 count = 1

 fact = 1

 while count <= n:

 yield fact

 count = count + 1

 fact = fact * count

 >>> print “Factorial program using generators.”

 >>> for i in factorial(5):

 print i


Factorial program using generators.






June 25, 2011

Python: Exception handling

Filed under: Python — shadiyya @ 4:30 am

In a program, even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions. All modern computer languages, and most ancient ones, have built-in constructs and methods for the handling errors or exceptions. Errors will couse the program to fail or produce meaningless results. Most exceptions are not handled by programs, however, and result in error messages as shown here:

>>> 10 * (1/0)
Traceback (most recent call last):
File “”, line 1, in ?
ZeroDivisionError: integer division or modulo by zero
>>> 4 + spam*3
Traceback (most recent call last):
File “”, line 1, in ?
NameError: name ‘spam’ is not defined
>>> ‘2’ + 2
Traceback (most recent call last):
File “”, line 1, in ?
TypeError: cannot concatenate ‘str’ and ‘int’ objects
The last line of the error message indicates what happened. Exceptions come in different types, and the type is printed as part of the message: the types in the example are ZeroDivisionError, NameError and TypeError. The rest of the line provides detail based on the type of exception and what caused it.

Handling exceptions

In Python a programmer can raise an exception at any point in a program. Python scripts can get away from errors by wrapping a portion of the main program in an exception handler to print a nicely formatted error.
The above example, asks the user for input until a valid integer has been entered, but allows the user to interrupt the program.
>>> while True:
…         try:
…             x = int(raw_input(“Please enter a number: “))
…             break
…         except ValueError:
…             print “That was not a valid number. Try again…”

The try statement works as follows:

  • First, the try clause (the statement(s) between the try and except keywords) is executed.
  • If no exception occurs, the except clause is skipped and execution of the try statement is finished.
  • If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after theexcept keyword, the except clause is executed, and then execution continues after the try statement.
  • If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.

A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. An except clause may name multiple exceptions as a parenthesized tuple also. The last except clause may omit the exception name, to serve as a wildcard. For example:


f = open(‘myfile.txt’)
s = f.readline()
i = int(s.strip())
except ValueError:
print “Could not convert data to an integer.”


print “Unexpected error:”

The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.
>>> for arg in sys.argv[1:]:
…          try:
…                f = open(arg, ‘r’)
…          except IOError:
…               print ‘cannot open’, arg
…          else:
…               print arg, ‘has’, len(f.readlines()), ‘lines’
…               f.close()

When an exception occurs, it may have an associated value, also known as the exception’s argument. The presence and type of the argument depend on the exception type. Exception handlers don’t just handle exceptions if they occur immediately in the try clause, but also if they occur inside functions that are called (even indirectly) in the try clause. For example:
>>> def this_fails():
…           x = 1/0

>>> try:
…          this_fails()
… except ZeroDivisionError as detail:
…          print ‘Handling run-time error:’, detail

Handling run-time error: integer division or modulo by zero

Raising Exceptions
The raise statement allows the programmer to create an exception. The argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives fromException). If we want to determine whether an exception was raised but don’t intend to handle it, just a raise statement allows us to re-raise the exception.
>>> try:
…          raise NameError(‘HiThere’)
… except NameError:
…          print ‘An exception flew by!’
…          raise

An exception flew by!
Traceback (most recent call last):
File “”, line 2, in ?
NameError: HiThere

User-defined exceptions
We can define new exception classes. When creating a module that can raise several distinct errors, it is a good idea to create a base class for exceptions defined by that module, and subclass to create specific exception classes for different error conditions.

class Error(Exception):

“””Base class for exceptions in this module.”””

class InputError(Error):

“””Exception raised for errors in the input.
expr — input expression in which the error occurred
msg — explanation of the error

def __init__(self, expr, msg):

self.expr = expr
self.msg = msg

class TransitionError(Error):

“””Raised when an operation attempts a state transition that’s not
prev — state at beginning of transition
next — attempted new state
msg — explanation of why the specific transition is not allowed

def __init__(self, prev, next, msg):

self.prev = prev = next
self.msg = msg

Cleaning up
The try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances.
>>> try:
…          raise KeyboardInterrupt
… finally:
…          print ‘Goodbye, world!’

Goodbye, world!
A ‘finally’ clause is always executed before leaving the try statement, whether an exception has occurred or not.

June 24, 2011

Functional programming in Python

Filed under: Python — shadiyya @ 2:31 am

Python supports functional programming paradigm which treats computation as mathematical evaluation of functions. Functions are first-class objects in Python. That is they have attributes and can be referenced and assigned to variables. Python also supports higher-order functions, that can accept other functions as arguments and return functions to the caller.

Lambda function

Python supports the creation of functions that are not bound to a name at runtime, using a construct called “lambda”. The lambda definition does not include a “return” statement — it always contains an expression which is returned. Also we can put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all.

>>> ls = [2,18,9,22,17,24,8,12,27]

>>> print filter(lambda x: x%3 == 0, ls)

[8, 9, 24, 12, 27]

Lambda functions are just needed where they have been created. Lambda functions are mainly used in combination with the functions filter(), map() and reduce().

Examples of higher order functions:

1. For customized sorting in Python, both the  sorted() function and the list’s .sort() method accept a key argument. The value passed to this argument needs to be a function object that returns the sorting key for any item in the list or iterable.

For example with a list of strings, specifying key=len (the built in len() function) sorts the strings by length, from shortest to longest.

strs = [‘ccc’, ‘aaaa’, ‘d’, ‘bb’]

print sorted(strs, key=len)

[‘d’, ‘bb’, ‘ccc’, ‘aaaa’]
2. filter()

syntax: filter(function, sequence)

This function returns those items of sequence for which function(item) is true.  If function is None, return the items that are true.If sequence is a tuple or string, return the same type, else return a list.

>>> def odd(n):
return n % 2
>>> li = [1, 2, 3, 5, 9, 10, 256, -3]
>>> filter(odd, li) [1, 3, 5, 9, -3]

3. map()

The map() function returns a list of the results of applying the function to the items of the argument sequence(s). If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each sequence, substituting None for missing values when not all sequences have the same length. If the function is None, return a list of the items of the sequence (or a list of tuples if more than one sequence).

>>> ls = [2,18,9,22,17,14,8,12,27]

>>> print map(lambda x: x * 2 + 10, ls)

[14, 46, 28, 54, 44, 58, 26, 34, 64]
4. reduce()

It applies a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.

>>> ls = [2,18,9,22,17,14,8,12,27]

>>> print reduce(lambda x,y: x+y, ls)


June 20, 2011

Python strings: Some basic exercises

Filed under: Python — shadiyya @ 6:05 pm

Here are some basic exercises on strings:

# A. donuts
# Given an int count of a number of donuts, return a string
# of the form ‘Number of donuts: <count>’, where <count> is the number
# passed in. However, if the count is 10 or more, then use the word ‘many’
# instead of the actual count.
# So donuts(5) returns ‘Number of donuts: 5’
# and donuts(23) returns ‘Number of donuts: many’

def donuts(count):
if count >= 0:
if count < 10:
return ‘Number of donuts: %d’ %(count)
return ‘Number of donuts: many’

# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so ‘spring’ yields ‘spng’. However, if the string length
# is less than 2, return instead the empty string.

def both_ends(s):
if len(s) > 1:
s1= s[0:2] + s[-2:]
return s1
return ”

# C. fix_start
# Given a string s, return a string
# where all occurences of its first char have
# been changed to ‘*’, except do not change
# the first char itself.
# e.g. ‘babble’ yields ‘ba**le’
# Assume that the string is length 1 or more.

def fix_start(s):
s2 = s[1:]
a=s[0] + s2.replace(s[0],’*’)
return a

# D. MixUp
# Given strings a and b, return a single string with a and b separated
# by a space ‘<a> <b>’, except swap the first 2 chars of each string.
# e.g.
#   ‘mix’, pod’ -> ‘pox mid’
#   ‘dog’, ‘dinner’ -> ‘dig donner’
# Assume a and b are length 2 or more.

def mix_up(a,b):
c=b[0:2] + a[2:] + ‘ ‘ + a[0:2] + b[2:]
return c

# D. verbing
# Given a string, if its length is at least 3,
# add ‘ing’ to its end.
# Unless it already ends in ‘ing’, in which case
# add ‘ly’ instead.
# If the string length is less than 3, leave it unchanged.
# Return the resulting string.

def verbing(s):
if len(s)>=3:
if s[-3:] == ‘ing’:
s = s + ‘ly’
s = s + ‘ing’
return s

# E. not_bad
# Given a string, find the first appearance of the
# substring ‘not’ and ‘bad’. If the ‘bad’ follows
# the ‘not’, replace the whole ‘not’…’bad’ substring
# with ‘good’.
# Return the resulting string.
# So ‘This dinner is not that bad!’ yields:
# This dinner is good!

def not_bad(s):
n1 = s.find(‘ not ‘)
n2 = s.find(‘ bad’)
if n1 != -1 and n2 != -1 and n1 < n2:
s = s.replace(s[n1:(n2+4)], ‘ good’)
return s

if lb%2 == 0:
fb = b[0:(lb/2)]
bb = b[lb/2:]
fb = b[0:(lb/2+1)]
bb = b[(lb/2+1):]
return fa + fb + ba + bb

# The test() function is used in main() to print
# what each function returns vs. what it’s supposed to return.

def test(got,expected):
if got == expected:
prefix = ‘OK’
prefix = ‘X’
print ‘%s got: %s expected: %s’ %(prefix, got, expected)

# main() calls the above functions using the above test() to
# check if the result is correct or not.

def main():

print ‘donuts’
test(donuts(10), ‘Number of donuts: many’)

print ‘both_ends’
test(both_ends(‘a’), ”)

print ‘fix_start’
test(fix_start(‘babble’), ‘ba**le’)

print ‘mix_up’
test(mix_up(‘gnash’, ‘sport’), ‘spash gnort’)

print ‘verbing’

print ‘not_bad’
test(not_bad(‘This movie is not so bad’), ‘This movie is good’)

print ‘front_back’
test(front_back(‘abcde’,’xyz’), ‘abcxydez’)


June 8, 2011

Object oriented programming and methods

Filed under: Python — shadiyya @ 10:33 am

A method is a function that is associated with a particular class. Methods are semantically the same as functions, but there are two syntactic differences:

  • Methods are defined inside a class definition in order to make the relationship between the class and the method explicit.
  • The syntax for invoking a method is different from the syntax for calling a function.

Here are some examples of methods:

1.  __init__ method

The init method (short for “initialization”) is a special method that gets invoked when an object is instantiated. For the Point class that represents a point in a plane,the __init__ method can be defined like this:

>>> class Point(object):

“”” represent a point in a plane “””

def __init__(self, x=0, y=0):

self.x = x

self.y = y

The parameters are optional, so if you call Point with no arguments, we get the default values.

__init__ method for time function might look like this:

# inside class Time:

def __init__(self, hour=0, minute=0, second=0):

     self.hour = hour

     self.minute = minute

     self.second = second

If we provide the arguments, it overrides the default values:

>>> time = Time (9,39,55)

>>> time.print_time()


2. __str__ method is a special method to return a string representation of an object. Here is a str method for the Point class.

# inside class Time:

def __init__(self, x=0, y=0):

self.x = x

self.y = y

def __str__(self):

return ‘(%d,%d)’ %(self.x, self.y)

We can check it by printing a point object:

>>> pt = Point(2,3)

>>> print pt

Operator overloading

By defining other special methods, we can specify the behavior of operators on user-defined types. For example, if we define a method named __add__ or the Time class, we can use the + operator on Time objects. As an example, for Point class the definition of __add__ would be like this:

# inside class Point:

def __add__(self,other):

a=self.x + other.x

b = self.y + other.y

return a,b

>>>pt1 = Point(4.8)

>>> pt2 = Point(5,2)

>>> print pt1 + pt2

June 5, 2011

User defined types in Python

Filed under: Python — shadiyya @ 11:03 am

We can define new types other than user defined types in Python. A user-defined type is also called a class. A class definition looks like this:

>>> class Point(object):

“””represents a point in a plane”””

This creates a type called Point that represents a point in a plane. This header indicates that the new class is a Point, which is a kind of object, which is a built-in type. The body is a docstring that explains what the class is for. To create a Point, call Point as if it were a function.

>>> blank = Point()

Creating a new object is called instantiation, and the object is an instance of the class. We can assign values to named elements of an object called attributes.

>>> blank.x = 3.0

>>> blank.y = 4.0  

As an example, here is a function called ‘distance’ that takes two Points as arguments and returns the distance between them.

>>> import math

>>>def distance(p1,p2):

x=p1.x – p2.x


dist= math.sqrt(x**2 + y**2)

print dist

Then, we can see how the function works by the following command lines:

>>> p1=Point()

>>> p2=Point()

>>> p1.x , p1.y = 4, 2

>>> p2.x , p2.y = 9, 10

>>> distance(p1, p2)

Next is another type named rectangle that represents a rectangle with attributes – width, height and corner.

>>> class Rectangle(object):

“””represent a rectangle.

attributes: width, height, corner”””

The below function named ‘move_rectangle’ takes a Rectangle and two numbers named dx and dy,and changes the location of the rectangle by adding dx to the x coordinate of corner and adding dy to the y coordinate of corner.

>>> def move_rectangle(rect, dx, dy):

rect.corner.x += dx

rect.corner.y += dy

return rect.corner

Here, ‘rect’ is a Point object that specifies the lower-left corner. We can assign values to the attributes as:

>>> rect = Rectangle()

>>> rect.width=40

>>> rect.height = 50

>>> rect.corner = Point()

>>> rect.corner.x = 30

>>> rect.corner.y = 10

The function call:

>>> move_rectangle(rect, 50, 40)

moves the corner of rectangle to a new position.

If we need to create a new Rectangle instead of modifying the old one, we can use a method in copy module called ‘deepcopy’ that copies not only the object but also the objects it refers to, and the objects they refer to, and so on.

>>> import copy

>>> rect1 = copy.deepcopy(rect)

>>> move_rectangle(rect1, 50, 40)

This creates a new rectangle object called rect1and retain the previous one.

Another example is a class called ‘Time’ that records the time of day. The class definition looks like this:

>>> class Time(object):

“””represents the time of day.

attributes: hour, minute, second”””

Here is a function called ‘print_time’ that takes a Time object and prints it in the form hour:minute:second

>>> def print_time(time)

Print ‘%g :%g:%g’ %(time.hour, time.minute, time.second)

To make ‘print_time’ a method, all we have to do is move the function definition inside the class definition.

>>> class Time(object):

>>> def print_time(time):

print ‘%.2d:%.2d:%.2d’ % (time.hour, time.minute, time.second)

Then, print_time can be used as a method:

>>> start = Time()

>>> start.hour = 9

>>>start.minute = 45

>>> start.second = 10

>>> start.print_time() 09:45:10

We can convert Time objects to integers and make the computation easy. Here is a function that converts Times to integers:

>>> def time_to_int(time):

minutes = time.hour * 60 + time.minute

seconds = minutes * 60 + time.second

return seconds

And here is the function that converts integers to Times:

>>> def int_to_time(seconds):

time = Time()

minutes, time.second = divmod(seconds, 60)

time.hour, time.minute = divmod(minutes, 60)

return time

A function namely  ‘increment’ which adds a given number of seconds to a Time object, can be written as:

>>> def increment(time1,seconds):


y=x + seconds


return z

And the function call is:

>>> t=increment(t1,25)

>>> print_time(t)

t1 is a time object. The function adds 25 seconds to t1 and return the resulting time.


1.1  Write a function called ‘mul_time’ that takes a Time object and a number and returns a new Time object that contains the product of the original Time and the number.

>>> def mul_time(time,n):

a = time_to_int(time)

b = a*n

c = int_to_time(b)

return c

1.2  Then use ‘mul_time’ to write a function that takes a Time object that represents the finishing time in a race, and a number that represents the distance, and returns a Time object that represents the average time per mile.

>>> def avg_race_time(time2,dist):

d = 1.0/dist

avg = mul_time(time2,d)

print ‘average time taken is: %d:%d:%d per mile’ %(avg.hour, avg.min, avg.second)

return avg

>>> avg_race_time(start, 5)

2.       Write a class definition for a Date object that has attributes day, month and year. Write a function called ‘increment_date’ that takes a Date object and an integer ‘n’, and returns a new Date object that represents the day ‘n’ days after date.

>>> class Date(object):

“””Represents date

attributes: day, month, year


>>> date=Date()


>>> date.month=2

>>> date.year=2011

>>> dic_norm=dict()

>>> dic_norm={1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31}

>>> dic_leap=()

>>> dic_leap=={1:31, 2:29, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31}

>>> def leap(year):

if year%4 == 0:

if year%100 != 0:

dic = dic_leap

return dic

elif year%400 == 0:

dic = dic_leap

return dic

dic = dic_norm

return dic

>>> def add_days(a,n):






while (b-c) > 0:


if e==12:





return b,e,f

>>> def increment_date(dt,n):

print ‘%d-%d-%d , (%d)’ %(, dt.month, dt.year, n)

x,y,z = add_days(, n)

d=Date() = x

d.month = y


print ‘%d-%d-%d’ %(, d.month, d.year)

return d

>>> increment date(date, 87)

June 2, 2011

Python: Tuples

Filed under: Python — shadiyya @ 11:55 am

A tuple is an immutable sequence of values. The values can be any type, and they are indexed by integers. To return multiple values from a function, we can use tuple as returning value.

Functions can take a variable number of arguments. A parameter name that begins with * gathers arguments into a tuple. For example, ‘printall’ takes any number of arguments and prints them:

>>> def printall(*args):

print args

The complement of gather is scatter. If you have a sequence of values and you want to pass it to a function as multiple arguments, you can use the * operator.

>>> t = (7, 3)

>>> divmod(*t)

(2, 1)

‘zip’ is a built-in function that takes two or more sequences and “zips” them into a list of tuples where each tuple contains one element from each sequence.

This example zips a string and a list:

>>> s = ‘abc’

>>> t = [0, 1, 2]

>>> zip(s, t)

[(‘a’, 0), (‘b’, 1), (‘c’, 2)]

The result is a list of tuples where each tuple contains a character from the string and the corresponding element from the list.

Here is a function called ‘most_frequent’ that takes a file (t.txt) and prints the letters in decreasing order of frequency.

>>>def most_frequent(a):

for b in a:




for d in c:

if d==’ ’:


elif d not in l:





for i in range(len(l)):

if l[i]==d:

l1[i] +=1


i += 1

z = zip(l1, l)

z.sort(reverse = True)

for g,h in z:

print g,h

If we call this function as:

>>> most_frequent(‘t.txt’)

it will print all the letters in the file in decreasing order of frequency.

« Previous PageNext Page »

Blog at

%d bloggers like this: