# [Tutor] How to manipulate a variable whose value depends on next values of list using LC or reduce()

Shashwat Anand anand.shashwat at gmail.com
Fri Oct 30 01:07:14 CET 2009

```Shashwat Anand to Bangalore
show details 5:31 AM (2 minutes ago)

*# 1:*

>>> sum([1, 2, 3], 4)
10

How does it actually work ?
( ( (1 + 2) + 3) + 4)  or ( ( (4 + 1) + 2 + 3)

sum( ) -> sum: (sequence[, start]), so shouldn't 4 be the 'start' that's
second case ?

"Note that sum(range(n), m) is equivalent to reduce(operator.add, range(n),
m)"

>>> sum ( [ [ 1 ], [ 2, 3 ] ], [ ])
[1, 2, 3]
What's happening here exactly ?
[ 1] + [2, 3] = [1, 2, 3] is understandable, but why do we pass a [ ] as a
[start] parameter to do so ?

>>> reduce(operator.mul, [1, 2, 3], 4)
24
how does it works ?
( ( (1 * 2) * 3) * 4) or (((4 * 1) * 2) * 3)

*# 2:*

I wrote an LCM function of mine as follows:

import fractions
def lcm(mylist):
# lcm by defination is Lowest Common Multiple
# lcm (a*b) = a*b / gcd(a*b)
# lcm (a, b, c) = lcm(lcm(a, b), c)
# the function lcm() returns lcm of numbers in a list
# for the special case of two numbers, pass the argument as lcm([a, b])
sol = 1
for i in mylist:
sol = sol * i / fractions.gcd(sol, i)
return sol

print lcm(range(1, 11))  #gives lcm of numbers (1, 2, 3....,9 ,10)
print lcm([2, 3])             #gives lcm of two numbers, a special case
print lcm([2, 5, 6, 10])   #gives lcm of a random list

However I also did a dirty hack as an alternate approach :

import fractions
l = [1]
print max( ( l[i-2], l.append(l[-1] * i / fractions.gcd(l[-1], i ) ) ) for i
in range(2, 12) )[0]
# prints the LCM of list (1, 10)

However to shorten the code i made it totally unpythonic.
Can reduce( ) or any other function be of help ?

Let me take a test-case as an example:
I want to multiple all the content of a given list,
now say my list is lst = [2, 3, 9]
I can do:

sol = 1
for i in lst:
sol *= i
print sol

However this can also be done as:

>>>reduce( operator.mul, lst)

Can it be done via List Comprehension or we have to do dirty hacks as
mentioned above :(
Can the LCM function be reduced ?

*The point is if we insert a variable( sol here in both test case and LCM
case), which changes its values dynamically depending upon the next values
of the list, how can I calculate so without going through the long way of
using for-construct*, which makes me feel as though i'm coding in C. reduce(
) or even sum( ) does helps in some cases but it constrains me as per my
requirement. Any pointers ?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091030/2c55e977/attachment.htm>
```