msg95762 - (view) |
Author: Christoph Zwerschke (cito) * |
Date: 2009-11-27 10:47 |
In the section "Using the batteries" of the "Idioms and Anti-Idioms in Python" document (http://docs.python.org/dev/howto/doanddont.html#using-the-batteries), the reduce statement is used for summing up numbers as an example. I think this is rather an anti-example, because Python already has a sum function built-in, i.e. reduce(operator.add, nums)/len(nums) can be written much simpler as sum(nums)/len(nums). |
|
|
msg96286 - (view) |
Author: Ezio Melotti (ezio.melotti) *  |
Date: 2009-12-12 08:22 |
The example alone can't be fixed, because half of the section talks about how useful reduce() is. The whole document should IMHO be rewritten, possibly using some of the examples in http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html I already asked to David and he said that the license (CC-BY-SA) allows to do that. If you agree to rewrite it and no one else volunteer, I can try to do it, but I don't know when I'll have time. |
|
|
msg96287 - (view) |
Author: Raymond Hettinger (rhettinger) *  |
Date: 2009-12-12 08:40 |
FWIW, I think the example is fine as-is. It could be changed to a product example: reduce(operator.mul, range(1, n+1)) or somesuch. Also, the text could be modified to mention sum(). But it is also fine if the example is unchanged, it does show how reduce() works. Recommend closing or just having a very minor edit. |
|
|
msg96308 - (view) |
Author: Christoph Zwerschke (cito) * |
Date: 2009-12-12 21:41 |
My point was that the passage starts with "there are also many useful built-in functions people seem not to be aware of for some reasons" and then it looks like the author himself was not aware of sum() for some reason because he gives calculating a sum with reduce() as a "classical example". It's very hard to come up with good examples for reduce() and I think in newer Python versions it has been demoted from builtin to functools, so it's not a good example for a useful built-in fuction anyway. |
|
|
msg115840 - (view) |
Author: Éric Araujo (eric.araujo) *  |
Date: 2010-09-08 01:57 |
I agree with Raymond that the example should be kept. We could add a comment explaining the difference with sum: reduce + operator.add works with all types. (sum would be marked up so that a link gets generated.) Is there a subsection about functional programming yet? reduce, filter and map are not always easy to use, especially now that they are lazy and thus can’t be used as a poor man’s for loop (i.e. for side effects, no to build a list). Such a section would be short and link to the functional programming howto. In the long term, integrating David Goodger’s document into the main docs so that it gets more exposure and more updates seems very useful to me. |
|
|
msg120093 - (view) |
Author: Raymond Hettinger (rhettinger) *  |
Date: 2010-10-31 22:02 |
Fixed in r86070, r86071, and r86072. |
|
|