[Tutor] simple math but I can't quite get it
Michael P. Reilly
arcege@shore.net
Sat, 10 Feb 2001 08:53:53 -0500 (EST)
> There are other ways of adding numbers; one of these ways is the
> "functional" approach:
>
> ###
> >>> def add(x, y): return x + y
> ...
> >>> sum = reduce(add, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
> >>> sum
> 55
> ###
>
> This, too, tells Python to: "Reduce all those list elements into a single
> thing, by using the add() function repeatedly." It might be a little
> weird because we're feeding the add() function itself into the reduce()
> function, but it's not too hard once you play with it.
>
> Here's another example of using reduce to find the product of all numbers
> in a list:
>
> ###
> >>> def mul(x, y): return x * y
> ...
> >>> product = reduce(mul, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
> >>> product
> 3628800
> ###
These functions are also built in to the operator module.
>>> l = range(1, 11)
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> import operator
>>> reduce(operator.add, l)
55
>>> reduce(operator.mul, l)
3628800
>>>
Most all the Python operators have function analogs in the `operator'
module.
-Arcege
--
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager | Email: arcege@shore.net |
| Salem, Mass. USA 01970 | |
------------------------------------------------------------------------