Saturday, March 16, 2013

imap and map in python.

  •  The imap() function returns an "iterator" that calls a function on the values in the input
    iterators and returns the results.
  • Like map() but stops when the shortest iterable is exhausted instead
of filling in None for shorter iterables.The sentence is bit odd but let's go through it.

>>>from itertools import *
>>> list(imap(pow, xrange(10), count()))
[1, 1, 4, 27, 256, 3125, 46656, 823543, 16777216, 387420489]


  1. pow is a builtin function which caluclates power of two numbers(pow(2,5==>2**5==>32)
  2. In the above example we passed 3 arguments,1 pow function,xrange(10) ,count.
  3. imap maps the power function over those other two arguments.This is equivalent to pow(xrange(10),count())
  4. xrange(10) will exhaust after 10 values,despite count() being infinite iteration it stops because xrange(10) has exhausted.
  5. we make a list of all the powers by calling list()
  6.  
Input:
#!usr/bin/env/python
from itertools import *
#Using imap from itertools.
print 'Triples:'
for i in imap(lambda x:3*x,xrange(5)):
    print i
print "\nMultiples:"
for i in imap(lambda x,y:(x, y, x*y), xrange(5), xrange(5,10)):
    print '%d * %d = %d' % i
print "\n Zip"
print list(map(pow, xrange(10), count()))
Output:
Triples:
0
3
6
9
12

Multiples:
0 * 5 = 0
1 * 6 = 6
2 * 7 = 14
3 * 8 = 24
4 * 9 = 36

 Zip
Traceback (most recent call last):
  File "/home/ubuntu/Desktop/map_imap.py", line 11, in 
    print list(map(pow, xrange(10), count()))
TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'int'
[Finished in 0.2s with exit code 1]
The error is expected because count() is infinite iteration,but xrange() is exhausted so it can't perform operations which have "None" argument.
     











Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

No comments:

Post a Comment