Search code examples
pythonfunctionpalindrome

Function to generate a palindrome


I have this following that I can't seem to solve correctly. I have to write a function that takes a positive integer n as an input and checks if it is a palindrome (a number that's the same forward and backward). If it is, I have to return this number. If it isn't, I have to calculate the sum of the original number with the reversed number. This step is repeated until the result is a palindrome. This is the code I have so far:

x = input("Enter a positive integer: ")

def generate_palindrome(n):
    if n == n[::-1]:
        return n
    else:
        while n != n[::-1]:
            r = n[::-1]
            int(n) += int(r)
    return n

generate_palindrome(x)

Of course this returns an error, since int(n) += int(r) is not possible. However, when not using int, it adds it as a string and that's also incorrect.

I'm not sure how far I'm off with the solution. How can I implement this correctly?


Solution

  • You are close. You just need another variable for the integer version of your string.Then just be clear which holds a string and which holds an integer:

    def generate_palindrome(n):
        if n == n[::-1]:
            return n
        else:
            while n != n[::-1]:   # n needs to be a string for this to work
                r = int(n[::-1])  # r and s need to be numbers for correct addition
                s = int(n)
                n = str(r + s)    # n needs to still be a string for the next loop iteration
        return n
    
    generate_palindrome("989")
    # '989'
    
    generate_palindrome("98")
    # '8813200023188'
    

    FWIW, I don't know that this is always guaranteed to return a reasonably sized number for every input. For example, I gave up on generate_palindrome("5798").