Find the palindrome numbers of a given range

Question:

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



Asked By: user249018

||

Answers:

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

Edit: I just realised, you also have a while loop that never ends. Replace your while loop with an if statement, and then you see where the problem in your logic is.

Answered By: Jeanot Zubler
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.