1

On the Literate Programs site, I was looking at the Python code for the GCD algorithm.

def gcd(a,b):
        """ the euclidean algorithm """
        while a:
                a, b = b%a, a
        return b

What is going on in the body? Expression evaluation? Is it a compressed form of another structure?

mbubb
  • 13
  • 3
  • 1
    [link](http://en.literateprograms.org/Euclidean_algorithm_(Python)) – mbubb May 30 '14 at 20:38
  • There's no structure. it's just parallel assignment `x, y = 3, 4` is the same as doing `x = 3` and `y = 4` separately. – Marc B May 30 '14 at 20:40
  • Do you mean the multiple assignment or the numeric evaluation as logical value? – Mephy May 30 '14 at 20:40
  • Thank you - I thought it was something like the 'swap variables without a temp var' idea. Which uses tuples: a, b, c = b, c, a – mbubb May 30 '14 at 20:42
  • Maybe it is Friday afternoon - but I just don't get it. "While a exists give me an 'a' and a 'b' which is modulus b over a ..." – mbubb May 30 '14 at 20:44
  • OH - Thank you - it *is* like a, b = b, a . I was reading it as 3 expressions not 4. it is clear now. I get it – mbubb May 30 '14 at 20:46
  • (umm - how do I show appreciation and close this?) – mbubb May 30 '14 at 20:47
  • @mbubb - You would accept the most helpful answer by clicking the check next to it. Doing so lets people know that this problem is solved. –  May 30 '14 at 21:15

3 Answers3

2

There are two things going on here:

            a, b = b%a, a

First, a tuple is created with the contents (b%a, a). Then the contents of that tuple are unpacked and assigned to the names a and b.

bgporter
  • 35,114
  • 8
  • 59
  • 65
  • 1
    Thank you - I was reading it as 3 expressions seperated by commas - I was not seeing: x,y = y,x – mbubb May 30 '14 at 20:50
1

Looks like shorthand for:

while a > 0:
    temp = a
    a = b%a
    b = temp
return b
Andrew
  • 4,953
  • 15
  • 40
  • 58
  • Where does the temp come in? ;) – Dair May 30 '14 at 20:42
  • It stores the old value of `a` so that when `a` is overwritten, we still have its original value for storing into `b`. The Python shorthand in the question doesn't need it but if we split it up like this we need to introduce this separate variable. – Andrew May 30 '14 at 20:43
  • No, I mean look at your code... `temp = a`, you mutate `a` and then take the mutated `a` and assign it `b`. – Dair May 30 '14 at 20:44
0

a is receiving the result of b%a while b is receiving the value of a

Works the same as:

while a > 0:
    tmp = a
    a = b%a
    b = tmp
return b

See this post for more information on switching variables: Is there a standardized method to swap two variables in Python?

Community
  • 1
  • 1
julienc
  • 19,087
  • 17
  • 82
  • 82