Reputation: 557
I want to find the palindrome numbers of a given range of integers without reversing the number. I want to rather check a condition going from digit to digit. If I use an if-else condition I get the numbers for which the condition holds only for one digit and not all of them. In order to make the condition hold for all digits I was tempted to use a while loop. But still I can not get the list of palindromes, the while loop running too long. Can somebody tell me what is wrong and what should I correct ? Thanks. Here is the code:
def pal():
s = []
for i in range(100, 10000):
for j in range(len(str(i))):
while str(i)[j] == str(i)[len(str(i)) - (j+1)]:
s.append(i)
return s
print(pal())
Upvotes: 1
Views: 860
Reputation: 1383
You are calling append for every digit. Something like this is more sensible:
def pal():
palindromes = []
for i in range(100, 10000):
s = str(i)
palindrome = True
for j in range(len(s)//2):
if s[j] != s[-(j+1)]:
palindrome = False
if palindrome:
palindromes.append(s)
return palindromes
You also have a while loop that never ends. Replace your while loop with an if statement (as in my example), then you see where the problem in your logic is.
Upvotes: 2