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

Dave Angel davea at ieee.org
Fri Oct 30 17:25:42 CET 2009

```Shashwat Anand wrote:
> Shashwat Anand to Bangalore
> show details 5:31 AM (2 minutes ago)
>
> <snip>
> 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 = 
> print max( ( l[i-2], l.append(l[-1] * i / fractions.gcd(l[-1], i ) ) ) for i
> in range(2, 12) )
> # 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 ?
>
>
Starting where Alan left off,

def lcm(mylist):
def lcm2(a, b):
return a*b / fractions.gcd(a, b)
return reduce(lcm2, mylist)

or, if you feel the need to get rid of the extra name,

def lcm(mylist):
return reduce(lambda a,b : a*b/fractions.gcd(a,b), mylist)

DaveA
```