2013-03-03 88 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