簡體   English   中英

這個最大公約數 (gcd) 如何在 python 中工作

[英]How this greatest common divisor (gcd) works in python

我從http://www.s-anand.net/euler.html中獲取了一段代碼,問題 5:

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

print gcd(10,20)

給 output:

10 20

20 10

10 0

10

為什么最后一行只打印“a”而不是 b。

你能解釋一下上面代碼中的 return 語句是如何工作的嗎?

我對“and”和“or”運算符有點困惑。

Python 的andor運算符使用一種起初有點令人困惑的短路求值

如果它們被寫成 function,它們會像這樣工作,除了它們甚至不評估正確的值,除非他們需要。

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

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

所以return b and gcd(b, a % b) or a這行可以寫得更詳細:

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

if temp_1:
    return temp_1
else:
    return a

如果你算出邏輯,這相當於尋找GCD的常用方法。 但是,除非您已經熟悉 Python,否則此代碼將難以閱讀,因此您可能希望避免使用這種樣式。

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

是舊的寫作方式:

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

因為 10 是您情況下的最大公約數,例如 gcd(10,20) 的結果

您的代碼(返回 b 和 gcd(...) 或 a)與以下內容相同:

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

另請注意, 分數模塊中有 gcd 方法

from fractions import gcd
print gcd(10,20)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM