2013-03-03 91 views
0

我有一個關於python優先級的問題。我有以下代碼:Python中的邏輯優先級

def gcdIter(a, b): 
    ans = min(a,b) 
    while ((a%ans is not 0) and (b%ans is not 0)): 
     ans -= 1 
    return ans 

我的問題是關於while邏輯語句。我添加了幾個括號,以確保表達式將按照我的想法進行評估,但不是。在兩個表達式都爲真之前,while循環正在被打破。我錯了嗎?

我找到了一種方法做同樣的事情,而無需使用兩個表達式中:

def gcdIter(a, b): 
    ans = min(a,b) 
    while ((a%ans + b%ans is not 0)) : 
     ans -= 1 
    return ans 

但我還是想知道爲什麼第一個代碼沒有運行,我認爲它應該的方式。

+0

「while循環在兩個表達式都是真的之前就被打破了」也許你對循環的工作方式感到困惑。 – thebjorn 2013-03-03 12:05:33

+0

* *條件爲「False」時,while循環將中斷。如果你希望它們都必須是'False',則使用'或'。 – sapi 2013-03-03 12:11:26

+0

問題解決。我用過,我應該用它。感謝大家在我的第一個問題中如此熱烈的歡迎! – 2013-03-03 13:35:03

回答

7

請勿使用身份驗證(isis not)測試數值相等。改爲使用==!=

while a%ans != 0 and b%ans != 0: 

is試驗對象標識(即兩個運算符是相同的蟒對象),這是不一樣的東西測試如果值等效

由於0也是在布爾上下文中考慮False,你甚至可以省略!=在這種情況下:

while a % ans and b % ans: 

fractions module已經有一個gcd()功能正確實現最大公約數算法:

from fractions import gcd 

print gcd(a, b) 

它使用Euclidian algorithm,蟒蛇風格:

def gcd(a, b): 
    """Calculate the Greatest Common Divisor of a and b. 

    Unless b==0, the result will have the same sign as b (so that when 
    b is divided by it, the result comes out positive). 
    """ 
    while b: 
     a, b = b, a%b 
    return a