[Tutor] How to manipulate a variable whose value depends on nextvalues of list using LC or reduce()
Alan Gauld
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)
> 10
>
> sum( ) -> sum: (sequence[, start]), so shouldn't 4 be the 'start' that's
> second case ?
Try help(sum):
>>> help(sum)
Help on built-in function sum in module __builtin__:
sum(...)
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
[1] + [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
> a
> [start] parameter to do so ?
Because the default start is 0 which is not a list so the addition would
fail.
>>> sum([[1],[2,3]],[])
[1, 2, 3]
>>> sum([[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)
> 24
> how does it works ?
>>> help(reduce)
Help on built-in function reduce in module __builtin__:
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a
sequence,
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
items
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! :-)
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list