Can anyone explain what the commas do, and when 'a' and 'b' are defined in this code http://dpaste.com/557932/? It's actually one of the soln on the Project Euler problem 5 thread which I don't understand. Using it to complement my 6.00 study. Thanks!
def gcd(a, b): while b != 0: a, b = b, a % b ## this is the same thing as ## a = b ## b = a % b ## this code decided to put it on one line by separating with a ',' return a def lcm(a, b): return a*b/gcd(a, b) print reduce(lcm, range(1, 20+1))
it's called tuple unpacking: see the bottom of this, http://docs.python.org/release/1.5.1p1/tut/tuples.html
here is another good one: http://en.wikibooks.org/wiki/Python_Programming/Tuples#Packing_and_Unpacking
sorry bwCA, but i don't understand where's the tuple unpacking, and how a and b get their values?
ok bwCA, i thought about it again and know where the tuple unpacking is. i'm still trying to get by head around why it works because of the order of statements, but i should be fine. thanks again!
a,b = c,d Is equivalent to a=c b=d
http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#swap-values
Join our real-time social learning platform and learn together with your friends!