In: Computer Science
making a python code for this:
A palindrome is a sequence that reads the same backwards as forwards. Numbers can also be palindromes if we consider their digits as a sequence, for example 12121 and 8228 are palindromes.
We can find palindromes from an initial seed number using the reverse and add method: choose a number, reverse its digits and add it to the original. If the sum is not a palindrome (which means, it is not the same number from left to right and right to left), repeat this procedure.
For example:
195 Initial number
+591
—–—
786
+687
—–—
1473
+3741
—–—–
5214
+4125
—–—–
9339 Resulting palindrome
In this particular case the palindrome ‘9339’ appeared after the 4th addition. This method leads to palindromes in a few iterations for almost all integers. But there are interesting exceptions. 196 is the first number for which no palindrome has been found. It is not proven though, that there is no such a palindrome.
You must write a program that give the resulting palindrome and the number of iterations (additions) to compute the palindrome.
You might assume that all tests data on this problem:
Input
The first line will have a number N (0 < N <= 100), where N is the number of test cases. The next N lines will each have one number, P, which is the initial number from which to compute a palindrome.
The file could contain non-integer data, which shall be processed as indicated below.
Output
For each of the N tests you will output one line as follows:
Sample Input
4
195
265
2.7
750
Sample Output
4 9339
5 45254
Bad data: 2.7
3 6666
Thanks for the question. Below is the code you will be needing Let me know if you have any doubts or if you need anything to change. Thank You ! =========================================================================== # function takes in a number and returns the iterations it took to find a palindrome and the # palindrome number as tuple, for all non-integer it returns 'Bad Data:' def find_palindrome(number): iterations = 0 try: to_int = int(number) if to_int != number: return 'Bad data:', number except: return 'Bad data:', number while True: reverse = str(number)[::-1] reverse_int = int(reverse) if number == reverse_int: break else: iterations += 1 number = reverse_int + number return iterations, number def main(): iteration,num = find_palindrome(195) # test with 195 print('{} {}'.format(iteration,num)) iteration,num = find_palindrome(265) # test with 265 print('{} {}'.format(iteration,num)) iteration,num = find_palindrome(2.7) # test with 2.7 print('{} {}'.format(iteration,num)) iteration,num = find_palindrome(750) # test with 750 print('{} {}'.format(iteration,num)) main()
=========================================================================