this is my first post here. I’m new to Python and programming in general so I’m not sure where I went wrong. This is a solution I came up with to Problem #52 on Project Euler (I know it’s probably not the best way either). My problem with this code is that the while statement doesn’t break when it gets to the correct answer. It’ll catch it and give me the answer only if I started num with the correct answer: 142857, but when I initialize it with anything else it continues counting right past 142857. The strange thing is I used the same exact method to answer another Euler Problem and that one works just fine. Can anyone please tell me why this is happening here? Thanks!
def digits(number):
return [int(x) for x in str(number)]
def same_digits():
num = 1
x2 = sorted(digits(num*2))
x3 = sorted(digits(num*3))
x4 = sorted(digits(num*4))
x5 = sorted(digits(num*5))
x6 = sorted(digits(num*6))
while x2 != x3 != x4 != x5 != x6:
num += 1
print num
The variables
x2etc. are not changed inside the loop, so they will always keep their initial values. If you want their values to be recalculated whennumchanges, you need to move that code into the loop.Moreover, you are using comparison operator chaining here. The expression
is equivalent to
which probably isn’t what you want.