Search code examples
pythonpalindrome

Python Palindrome


So my task is to see and check a positive integer if its a palindrome. I've done everything correctly but need help on the final piece. And that the task of generating a new a palindrome from the one given given by the user. Am i on the right track with the while loop or should i use something else? So the result is if you put 192 it would give back Generating a palindrome.... 483 867 1635 6996

"""Checks if the given, positive number, is in fact a palindrome"""

def palindrome(N):
    x = list(str(N))
    if (x[:] == x[::-1]):
        return True
    else: return False 

"""Reverses the given positive integer"""

def reverse_int(N):
    r = str(N)
    x = r[::-1]
    return int(x)


def palindrome_generator():
    recieve = int(input("Enter a positive integer. "))
    if (palindrome(recieve) == True):
        print(recieve, " is a palindrome!")
    else:
        print("Generating a palindrome...")
        while palindrome(recieve) == False:
            reverse_int(recieve) + recieve

Solution

  • If I understand your task correctly, the following should do the trick:

    def reverse(num):
        return num[::-1]
    
    def is_pal(num):
        return num == reverse(num)
    
    inp = input("Enter a positive number:")
    
    if is_pal(inp):
        print("{} is a palindrome".format(inp))
    else:
        print("Generating...")
        while not is_pal(inp):
            inp = str(int(inp) + int(reverse(inp)))
            print(inp)
    

    The variable inp is always a string and only converted to int for the arithmetic.