Python中的逻辑优先级

Luc*_*iro 0 python syntax logical-operators python-2.7

我有一个关于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
Run Code Online (Sandbox Code Playgroud)

我的问题是关于while逻辑陈述.我添加了几个括号,以确保表达式将按照我的思维方式进行评估,但事实并非如此.在两个表达式都为真之前,while循环正在被中断.我错了吗?

在没有使用两个表达式的情况下,我找到了一种方法来做同样的事情:

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

但我仍然想知道为什么第一个代码没有按照我认为的方式运行.

Mar*_*ers 7

不要使用身份测试(isis not)来测试数字相等性.使用==!=代替.

while a%ans != 0 and b%ans != 0:
Run Code Online (Sandbox Code Playgroud)

is对象标识的测试(两个运算符都是相同的python对象),这与测试值是否相等不同.

因为在布尔上下文中0也考虑False过,所以!=在这种情况下甚至可以省略:

while a % ans and b % ans:
Run Code Online (Sandbox Code Playgroud)

fractions模块已经具有gcd()正确实现最大公约数算法的函数:

from fractions import gcd

print gcd(a, b)
Run Code Online (Sandbox Code Playgroud)

它使用欧几里德算法,python样式:

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
Run Code Online (Sandbox Code Playgroud)