繁体   English   中英

我的Python代码无法正常运行,我认为应该

[英]My Python code is not working like I think it should

我正在用Python弄湿自己,在过去一两个小时里,我一直在盯着这段代码。 即使我知道我的程序已生成正确的数字序列,即所谓的勾股三元组,逻辑也不会“抓住”三元组。 这是欧拉问题#9。

#https://projecteuler.net/problem=9
def main(num):
    i = num
    j = k = 0
    while i >= 0:
        while j >= k:
            print(i, ",", j, ",", k, ": ", i*i, "=", j*j + k*k) 
            if i*i == j*j + k*k & i > j > k: # this line here should detect the triple
                print("found")
                print(i, ",", j, ",", k)
                break
            j -= 1
            k += 1
        i -= 1
        j = 1000 - i
        k = 0


main(1000)
#The Pythagorean triple is 425, 375, 200, and the sum is 1000
#The product is 31875000

这条线显然在这里...

if i*i == j*j + k*k & i > j > k: #this line here should detect the triple

...即使程序正确生成了三元组,也不会返回true(425,375,200)

我确定我一定错过了完全显而易见的事情。

我认为您可能想使用逻辑和运算符and (Python等效于C和Java的&& ),而不是按位和运算符&

添加一些括号也可能有助于确保正在以所需的优先级对运算符进行评估。

以下行对我有用:

if (i*i == j*j + k*k) and (i > j > k): # should detect the triple

尝试使用以下代码用注释替换该行。 了解一件事-在python中,“ and”代替了C中的“ &&”。

如果((i ** 2)==((j ** 2)+(k ** 2)))和(i> j> k):

如果您的代码在逻辑上是正确的,那么这应该可以工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM