[英]Why is getattr() not working like I think it should? I think this code should print 'sss'
[英]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.