我对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 :(得分:7)
不要使用身份测试(is
或is not
)来测试数字相等性。请改用==
或!=
。
while a%ans != 0 and b%ans != 0:
is
测试对象标识(两个运算符都是相同的python对象),这与测试值等效的情况不同。
由于0
在布尔上下文中也被视为False
,因此在这种情况下甚至可以省略!=
:
while a % ans and b % ans:
fractions
module已经有一个gcd()
函数,可以正确实现最大公约数算法:
from fractions import gcd
print gcd(a, b)
它使用Euclidian algorithm,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