@@ -244,24 +244,22 @@ Compare::
244244More useful functions in :mod: `os.path `: :func: `basename `, :func: `dirname ` and
245245:func: `splitext `.
246246
247- There are also many useful built-in functions people seem not to be aware of for
248- some reason: :func: `min ` and :func: `max ` can find the minimum/maximum of any
249- sequence with comparable semantics, for example, yet many people write their own
250- :func: `max `/:func: `min `. Another highly useful function is
251- :func: `functools.reduce `. A classical use of :func: `reduce ` is something like
252- ::
253-
254- import sys, operator, functools
255- nums = list(map(float, sys.argv[1:]))
256- print(functools.reduce(operator.add, nums) / len(nums))
257-
258- This cute little script prints the average of all numbers given on the command
259- line. The :func: `reduce ` adds up all the numbers, and the rest is just some
260- pre- and postprocessing.
261-
262- On the same note, note that :func: `float ` and :func: `int ` accept arguments of
263- type string, and so are suited to parsing --- assuming you are ready to deal
264- with the :exc: `ValueError ` they raise.
247+ There are also many useful built-in functions people seem not to be aware of
248+ for some reason: :func: `min ` and :func: `max ` can find the minimum/maximum of
249+ any sequence with comparable semantics, for example, yet many people write
250+ their own :func: `max `/:func: `min `. Another highly useful function is
251+ :func: `functools.reduce ` which can be used to repeatly apply a binary
252+ operation to a sequence, reducing it to a single value. For example, compute
253+ a factorial with a series of multiply operations::
254+
255+ >>> n = 4
256+ >>> import operator, functools
257+ >>> functools.reduce(operator.mul, range(1, n+1))
258+ 24
259+
260+ When it comes to parsing numbers, note that :func: `float `, :func: `int ` and
261+ :func: `long ` all accept string arguments and will reject ill-formed strings
262+ by raising an :exc: `ValueError `.
265263
266264
267265Using Backslash to Continue Statements
0 commit comments