[Tutor] How to manipulate a variable whose value depends on nextvalues of list using LC or reduce()
alan.gauld at btinternet.com
Fri Oct 30 02:24:01 CET 2009
"Shashwat Anand" <anand.shashwat at gmail.com> wrote
>>>> sum([1, 2, 3], 4)
> sum( ) -> sum: (sequence[, start]), so shouldn't 4 be the 'start' that's
> second case ?
Help on built-in function sum in module __builtin__:
sum(sequence, start=0) -> value
Returns the sum of a sequence of numbers (NOT strings) plus the value
of parameter 'start'. When the sequence is empty, returns start.
So the badly named start parameter is the starting value of the sum.
So in your case it adds 4+ sum(1,2,3) = 4+6 = 10
>>>> sum ( [ [ 1 ], [ 2, 3 ] ], [ ])
> [1, 2, 3]
> What's happening here exactly ?
Its been given a list of lists so its adding the list elements
 + [2,3] -> [1,2,3]
And adding an empty list to a list returns the original list.
> [ 1] + [2, 3] = [1, 2, 3] is understandable, but why do we pass a [ ] as
> [start] parameter to do so ?
Because the default start is 0 which is not a list so the addition would
[1, 2, 3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>>> reduce(operator.mul, [1, 2, 3], 4)
> how does it works ?
Help on built-in function reduce in module __builtin__:
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the
of the sequence in the calculation, and serves as a default when the
sequence is empty.
So it starts with 4 then applies mul to [1,2,3]
4*1 -> [4,2,3]
4*2 -> [8,3]
8*3 -> 24
> I wrote an LCM function of mine as follows:
I'll let somebody else comment, its too late for me! :-)
Author of the Learn to Program web site
More information about the Tutor