Python中的逻辑优先级

2024-06-25 06:18:00 发布

您现在位置: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循环在这两个表达式都为true之前被中断。我错了吗?在

我找到了一种方法来做同样的事情,不用两个表达式:

^{pr2}$

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


Tags: and代码returnis表达式def方式not
1条回答
网友
1楼 · 发布于 2024-06-25 06:18:00

不要使用标识测试(isis not)来测试数值相等性。请改用==或{}。在

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

is测试对象标识(两个操作符都是同一个python对象),这与测试值是否等价于不是一回事。在

由于在布尔上下文中0也被认为是{},因此在这种情况下,您甚至可以省略{}:

^{pr2}$

^{} module已经有一个gcd()函数,它正确地实现了最大公约数算法:

from fractions import gcd

print gcd(a, b)

{a2,它使用^样式:

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

相关问题 更多 >