While loop or If code? Stuck with this function

113 Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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 
0
On

This is the best solution:

def  generate_palindrome(n):
        while True:
            number = list(str(n))
            num = ''
            if number[::-1] == number:
                for i in number:
                    num = num + i
                print(num)
                break
                print(a)
            else:
                for i in number:
                    num = num + i
                n = int(num) + int(num[::-1])
    
    generate_palindrome()
0
On

I think that you should've added a broken functionality to your while loop so that when a specific condition is achieved it breaks. And I think that the indentation of the last return statement is wrong. :)