diff options
author | Raymond Hettinger <python@rcn.com> | 2010-10-31 22:01:57 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2010-10-31 22:01:57 (GMT) |
commit | c6b6b5bf5add7d4062e132f4e4622bf83ae00e8d (patch) | |
tree | 4cc74630b18ebc44771531a18ff4afc61a24781d /Doc/howto | |
parent | 30bf6e836e4d671fd487673134c6041a6fe77204 (diff) | |
download | cpython-c6b6b5bf5add7d4062e132f4e4622bf83ae00e8d.zip cpython-c6b6b5bf5add7d4062e132f4e4622bf83ae00e8d.tar.gz cpython-c6b6b5bf5add7d4062e132f4e4622bf83ae00e8d.tar.bz2 |
Issue 7402: Improve reduce() example in the python idioms how-to.
Diffstat (limited to 'Doc/howto')
-rw-r--r-- | Doc/howto/doanddont.rst | 34 |
1 files changed, 16 insertions, 18 deletions
diff --git a/Doc/howto/doanddont.rst b/Doc/howto/doanddont.rst index 0f90cb3..365a6209d 100644 --- a/Doc/howto/doanddont.rst +++ b/Doc/howto/doanddont.rst @@ -244,24 +244,22 @@ Compare:: More useful functions in :mod:`os.path`: :func:`basename`, :func:`dirname` and :func:`splitext`. -There are also many useful built-in functions people seem not to be aware of for -some reason: :func:`min` and :func:`max` can find the minimum/maximum of any -sequence with comparable semantics, for example, yet many people write their own -:func:`max`/:func:`min`. Another highly useful function is -:func:`functools.reduce`. A classical use of :func:`reduce` is something like -:: - - import sys, operator, functools - nums = list(map(float, sys.argv[1:])) - print(functools.reduce(operator.add, nums) / len(nums)) - -This cute little script prints the average of all numbers given on the command -line. The :func:`reduce` adds up all the numbers, and the rest is just some -pre- and postprocessing. - -On the same note, note that :func:`float` and :func:`int` accept arguments of -type string, and so are suited to parsing --- assuming you are ready to deal -with the :exc:`ValueError` they raise. +There are also many useful built-in functions people seem not to be aware of +for some reason: :func:`min` and :func:`max` can find the minimum/maximum of +any sequence with comparable semantics, for example, yet many people write +their own :func:`max`/:func:`min`. Another highly useful function is +:func:`functools.reduce` which can be used to repeatly apply a binary +operation to a sequence, reducing it to a single value. For example, compute +a factorial with a series of multiply operations:: + + >>> n = 4 + >>> import operator, functools + >>> functools.reduce(operator.mul, range(1, n+1)) + 24 + +When it comes to parsing numbers, note that :func:`float`, :func:`int` and +:func:`long` all accept string arguments and will reject ill-formed strings +by raising an :exc:`ValueError`. Using Backslash to Continue Statements |