简体   繁体   中英

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. 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.

#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)

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 & .

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.

if ( (i ** 2 )==((j ** 2)+(k ** 2)) ) and (i > j > k):

If your code is logically correct,Then this should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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