[BangPypers] some doubts regarding python

Navin Kabra navin.kabra at gmail.com
Fri Oct 30 01:25:51 CET 2009


On Fri, Oct 30, 2009 at 5:31 AM, Shashwat Anand <anand.shashwat at gmail.com>wrote:

> *# 1:*
>
> >>> sum([1, 2, 3], 4)
> 10
>
> How does it actually work ?
> ( ( (1 + 2) + 3) + 4)  or ( ( (4 + 1) + 2 + 3)
>

( ( (4 + 1) + 2 + 3)
4 is the 'start'


> >>> sum ( [ [ 1 ], [ 2, 3 ] ], [ ])
> [1, 2, 3]
> What's happening here exactly ?
>

(([] + [1]) + [2, 3])



> [ 1] + [2, 3] = [1, 2, 3] is understandable, but why do we pass a [ ] as a
> [start] parameter to do so ?
>

The start defaults to 0.
So you'll get
((0 + [1]) + [2, 3])
which is a type error. Cannot add 0 to a list.


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

(((4 * 1) * 2) * 3)


>>>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 ?
>

Something like this should work:
def lcm2(a, b):
  return a*b/fractions.gcd(a,b)

def lcm(mylist):
  return reduce(lcm2, mylist)


More information about the BangPypers mailing list