Skip to content Skip to sidebar Skip to footer

How To Use Python Map Function To Generate The First 100 Powers Of Two Starting At 0 And Exclusive Of 100?

def map_twos(): def pwr(x): return 2**x map(pwr, range(0, 100)) print pwr.get[2] return pwr What is wrong. I don't know how do I use map function to get t

Solution 1:

pwr is a function. Even after you map it over a list, pwr is still a function. map(pwr, range(0, 100)) is the list you want. You can store it in a variable:

powers = map(pwr, range(0, 100))
print powers[2]
return powers

Solution 2:

map does not modify the existing list or function, but instead generates an iterator over the result (in Python 3). That means you need to store the result of map and eventually convert it to a list of you need to get the n-th element (in Python 3).

pwrs = map(lambda n: 1 << n, xrange(100))
print pwrs[2]

From the use of the print statement I figured you were using Python 2, so I left out the explicit conversion to a list and used xrange which returns an iterator (leading to better performance). In Python 3 xrange does not exist anymore however and range always returns an iterator. Also notice how I left out the lower boundary on the range function, because it defaults to 0. Instead of predefining a function I used a lambda here, which in turn uses a bitwise leftshift , because it is usually faster than using the ** (power) operator.

Post a Comment for "How To Use Python Map Function To Generate The First 100 Powers Of Two Starting At 0 And Exclusive Of 100?"