0

我有一个关于 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

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

4

1 回答 1

7

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

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

is测试对象身份(两个运算符是同一个 python 对象),这与测试值是否相等不同。

由于0也在False布尔上下文中考虑,因此在这种情况下您甚至可以省略!=

while a % ans and b % ans:

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

from fractions import gcd

print gcd(a, b)

它使用欧几里得算法,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
于 2013-03-03T12:04:34.937 回答