简体   繁体   中英

How this greatest common divisor (gcd) works in python

I have taken a piece of code from http://www.s-anand.net/euler.html , problem 5:

def gcd(a,b): 
    print a,b
    return b and gcd(b, a % b) or a

print gcd(10,20)

Giving output:

10 20

20 10

10 0

10

Why the last line prints only "a" not b.

Can you please explain how the return statement in above code works.

I am little bit confused with "and" and "or" operators.

Python's and and or operators use a type of short-circut evaluation that is a little confusing at first.

If they were written as function, they would work sort-of like this, except that they don't even evaluate the right value unless they need to.

def and(left, right):
    if left:
        return right
    else:
        return left

def or(left, right):
    if left:
        return left
    else:
        return right

So the line return b and gcd(b, a % b) or a could be written more verbosely as:

if b:
    temp_1 = gcd(b, a % b)
else:
    temp_1 = False

if temp_1:
    return temp_1
else:
    return a

If you work out the logic, this is equivalent to the common method for finding a GCD. However, unless you're already familiar with Python this code will be hard to read, so you might want to avoid this style.

b and gcd(b, a % b) or a

was the old way of writing:

gcd(b, a % b) if b else a

Because 10 is the greatest common divisor in your case, eg result of gcd(10,20)

Your code(return b and gcd(...) or a) is the same as:

def gcd(a,b): 
    print a,b
    if b:
        return b      
    else:
        res = gcd(b, a % b)
        return res if res else a

Also note that there gcd method in fractions module :

from fractions import gcd
print gcd(10,20)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM