Lambda Function and More

Problem 1


In [9]:
words = 'The quick brown fox jumps over the lazy dog'.split()
print words
stuff = []
for w in words:
    stuff.append([w.upper(), w.lower(), len(w)])

for i in stuff:
    print i


['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
['THE', 'the', 3]
['QUICK', 'quick', 5]
['BROWN', 'brown', 5]
['FOX', 'fox', 3]
['JUMPS', 'jumps', 5]
['OVER', 'over', 4]
['THE', 'the', 3]
['LAZY', 'lazy', 4]
['DOG', 'dog', 3]

Use list comprehension and lambda/map function to define stuff.


In [10]:
stuff = map(lambda w: [w.upper(), w.lower(), len(w)],words)
for i in stuff: print i


['THE', 'the', 3]
['QUICK', 'quick', 5]
['BROWN', 'brown', 5]
['FOX', 'fox', 3]
['JUMPS', 'jumps', 5]
['OVER', 'over', 4]
['THE', 'the', 3]
['LAZY', 'lazy', 4]
['DOG', 'dog', 3]

Problem 2

Use the filter function to remove all the vowels from the sentence


In [11]:
sentence = "It's a myth that there are no words in English without vowels."
vowels = 'aeiou'

In [12]:
result = filter(lambda x: x not in vowels, sentence)
print result


It's  myth tht thr r n wrds n Englsh wtht vwls.

Problem 3

Use the reduce function to find the produc of all the entries in the list [47,11,42,102,13]


In [13]:
print reduce(lambda x,y: x*y, [47,11,42,102,13])


28792764

In [15]:
# note that you can improve the speed of the calculation using built-in functions
# or better still: using the numpy module
from operator import mul
import numpy as np
a = range(1, 101)

print "\nreduce(lambda x, y: x * y, a)"
%timeit reduce(lambda x, y: x * y, a)   # (1)

print "\nreduce(mul, a)"
%timeit reduce(mul, a)                  # (2)

print "\nnp.prod(a)"
a = np.array(a)
%timeit np.prod(a)                      # (3)


reduce(lambda x, y: x * y, a)
100000 loops, best of 3: 17.9 µs per loop

reduce(mul, a)
100000 loops, best of 3: 11.1 µs per loop

np.prod(a)
The slowest run took 11.51 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.9 µs per loop

In [ ]: