5 ms·
where is times(range(1,11)) ? --- (apply #'* (-range 1 11)) python is weirdly halfway on 'math oriented' abstractions.
by agumonkey 11y ago
where is
times(range(1,11)) ?
---
(apply #'* (-range 1 11))
python is weirdly halfway on 'math oriented' abstractions.
- falcolas 11y agoJust not included in to the standard library (it doesn't really have a common use case), but certainly implementable, and without loops to boot! >>> def times(input): ... return reduce(lambda x, y: x*y, input, 1) ... >>> times(range(1,11)) 3628800
- agumonkey 11y agoOf course, it's just weird to see `sum` built-in all alone. They even have operator.mul so... >>> Prod = lambda xs: fp.reduce(op.mul, xs, 1) >>> Prod(range(1,11)) 362880
- TheLoneWolfling 11y agofrom functools import reduce from operators import mul def times(data): return reduce(mul, data)
- agumonkey 11y agoI'm not saying it's not possible, just that they stopped too early. >>> times([]) TypeError: reduce() of empty sequence with no initial value from functools import reduce from operators import mul def times(data): return reduce(mul, data) Proper neutral element: >>> times = lambda l: reduce(mul, l,1) >>> times([]) 1
- TheLoneWolfling 11y agoWhoops, but again as you say that is trivial to fix.
- agumonkey 11y agoIt's more about the philosophy, some languages recognize this way of thinking, having tiny bits of ~monoid-ic logic that works for N. Lists have neutral element (nil) and concatenative operation (cons). Arithmetic operations follow that. IMO they don't approach systems the same way.
- kedean 11y agoWhen in doubt, the answer is 'because Guido said so'. Benefits and downsides of having a BDFL on a language.
- agumonkey 11y agoHehe. Something funny I learned recently: Python reached version 1.0 in January 1994. The major new features included in this release were the functional programming tools lambda, map, filter and reduce. Van Rossum stated that "Python acquired lambda, reduce(), filter() and map(), courtesy of a Lisp hacker who missed them and submitted working patches".[9] https://en.wikipedia.org/wiki/History_of_Python#Version_1.0 https://en.wikipedia.org/wiki/History_of_Python#Version_1.0
- hga 11y agoAnd a dozen years later he wanted to wanting to purge them from the language, or at least lambda.