#### Python Map, Filter, and Reduce Flashcards

card 1 of 9

return x+y
def mul(x,y):
return x*y
def doby2(f,L):
return [ f(L[i],L[i+1]) for i in range(len(L)) ]
>>> doby2(mul,[10,20,30])

notice that parameter f is a function -- caller of doby2 says what f will be

IndexError: list index out of range

card 2 of 9

return x+y
def mul(x,y):
return x*y
def doby2(f,L):
return [ f(L[i],L[i+1]) for i in range(len(L)-1) ]
>>> doby2(mul,[10,20,30])

notice that parameter f is a function -- caller of doby2 says what f will be

[30,50]
[200,600]

card 3 of 9

def square(x):
return x*x
>>> map(square,[10,20,30])

map applies a function to every item in a list

[100,400,900]

card 4 of 9

return t+"Q"

remember how a string can be considered as a list of characters

['oneQ','moreQ','timeQ']
['CQ','AQ','SQ','UQ','AQ','LQ']

card 5 of 9

def EinX(x):
return 'e' in x.lower()
>>> map(EinX,["time","once","again","Easy","Does"])

each evaluation of EinX is done separately

[True,True,False,True,True]

card 6 of 9

def EinX(x):
return 'e' in x.lower()
>>> filter(EinX,["time","once","again","Easy","Does"])

each evaluation of EinX is done separately

['time','once','Easy','Does']

card 7 of 9

def EinXnot(x):
return 'e' not in x.lower()
>>> filter(EinXnot,["time","once","again","Easy","Does"])

each evaluation of EinXnot is done separately

['again']

card 8 of 9

>>> sum( map(len, "quoth the raven nevermore".split() ) )

build up the answer in steps: evaluate split, then map with len(), then sum

22

card 9 of 9

return x+y
def mul(x,y):
return x*y
>>> reduce(mul,[10,20,30],-1)
>>> reduce(add, "a text example".split(), 'X')

reduce's third argument is an initial value

55
-6000
'Xatextexample'

#### End of Problem Set

(use browser reload to restart this problem set)