Search code examples
pythoncountpalindrome

Palindrome chain length in Python coming up incorrect


I feel like this should work correctly but I get an error with the count being 1 less than it should be.

def palindrome_chain_length(n):
    count = 0
    while str(n) != str(n)[::-1] :
        n = n+n
        count += 1
    else:
        return count

Solution

  • If you just get count 1 less than you want, start with count = 1. And it seems to me that it should be:

    n += int(str(n)[::-1]) 
    

    instead of:

    n = n + n 
    

    (see comment @alfasin).