[英]My Python code is not working like I think it should
I am getting my feet wet in Python, and I have been staring at this code for the past hour or two. 我正在用Python弄湿自己,在过去一两个小时里,我一直在盯着这段代码。 Even though I know that my program has generated the correct sequence of numbers, the so called Pythagorean triple, the logic will not "grab" the triple.
即使我知道我的程序已生成正确的数字序列,即所谓的勾股三元组,逻辑也不会“抓住”三元组。 This is Euler problem #9.
这是欧拉问题#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
This line here apparently... 这条线显然在这里...
if i*i == j*j + k*k & i > j > k: #this line here should detect the triple
...does not return true, even if the program correctly generates the triplet (425,375,200) ...即使程序正确生成了三元组,也不会返回true(425,375,200)
I'm sure I must have missed something totally obvious. 我确定我一定错过了完全显而易见的事情。
I think you probably want to use the logical and operator and
(the Python equivalent of C and Java's &&
) instead of the bitwise and operator &
. 我认为您可能想使用逻辑和运算符
and
(Python等效于C和Java的&&
),而不是按位和运算符&
。
It might also help to add some brackets to make sure the operators are being evaluated with the precedence that you want. 添加一些括号也可能有助于确保正在以所需的优先级对运算符进行评估。
The following line works for me: 以下行对我有用:
if (i*i == j*j + k*k) and (i > j > k): # should detect the triple
Try replacing the line with comment with the following code. 尝试使用以下代码用注释替换该行。 Understand one thing- In python "and" is there instead of "&&" in C.
了解一件事-在python中,“ and”代替了C中的“ &&”。
if ( (i ** 2 )==((j ** 2)+(k ** 2)) ) and (i > j > k): 如果((i ** 2)==((j ** 2)+(k ** 2)))和(i> j> k):
If your code is logically correct,Then this should work. 如果您的代码在逻辑上是正确的,那么这应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.