Search code examples
python-3.xlistfunctionlist-manipulation

While loop or If code? Stuck with this function


I'm asked to write a function generate_palindrome() that takes a given positive integer number n and applies the following procedure to it:

(i) Check if the number is palindrome. If it is, then return it otherwise continue with the next step.

(ii) Reverse the number and calculate the sum of the original number with the reversed number.

(iii) Repeat from (i) (until a palindrome is found.)

I wrote this function:

def generate_palindrome(n):
    numbers = list(str(n))
    for i in range(len(numbers)):
        if numbers[i] == numbers[-i-1]:
            return n
        else:
            while numbers[i] != numbers[-i-1]:
                rev = list(reversed(numbers))
                rev_num = int(''.join(rev))
                n = n + rev_num
    return n

I don't know for what reason when I try a random number that is not already palindrome, the code doesn't respond, it's still running until an indefinite amount of time. I tried changing it with an if code but it doesn't iterate my function, so I think my only chance is with the while code, but maybe I'm the one who's wrong. What do you think?


Solution

  • Here you go:

    #!/usr/bin/env python3
    
    def generate_palindrome(num: int):
        if str(num) == str(num)[::-1]:
            return num
        else:
            while str(num) != str(num)[::-1]:
                rev = int(str(num)[::-1])
                num += rev
            return num
    
    if __name__ == '__main__':
        print(generate_palindrome(212)) # prints 212
        print(generate_palindrome(12)) # prints 33
        print(generate_palindrome(43)) # prints 77