First page Back Continue Last page Overview Graphics

Exercises for reduce()

Calculate the sum of the numbers from 1 to 100 by using reduce().

>>> reduce(lambda x, y: x+y, range(1,101))

5050

Calculate with reduce() the product of the numbers 1 to 9.

>>> reduce(lambda x, y: x*y, range(1,10))

362880

How can you determine the maximum of a list of numerical values by using reduce()?

>>> f = lambda a,b: a if (a > b) else b

>>> reduce(f, [47,11,42,102,13])

102

>>>