开发者

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 wor开发者_运维知识库ks.

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


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

was the old way of writing:

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


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.


Because 10 is the greatest common divisor in your case, e.g. 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜