Skip to main content
More easily parsed title
Link
syb0rg
  • 21.9k
  • 10
  • 113
  • 193

Check if Palindrome-inize a number ends up being a palindrome when added to its reverse

Tweeted twitter.com/StackCodeReview/status/758683255751204864
edited tags
Link
syb0rg
  • 21.9k
  • 10
  • 113
  • 193
Source Link

Check if a number ends up being a palindrome when added to its reverse

For example if I start with the number 146. I first reverse it, so it becomes 641. Then I add this to the original number to make 787 which is a palindrome. I would repeat the process if the answer is not a palindrome.

I made this program show how long it ran for when it finishes or is interrupted and also to write the output to a file called output.txt.

from sys import exit
from signal import SIGINT, signal
from timeit import default_timer


def n(x):

    counter = 0
    b = 0
    start = default_timer()

    def t(*args):

        end = default_timer()
        total = end - start
        print (total)
        
        with open('output.txt','w') as f:
            
            f.write('{}\n{}\n{}'.format(b, counter, total))

        exit(0)

    signal(SIGINT,t)


    while True:

        b += int(str(x)[::-1])
        
        if b == int(str(b)[::-1]):

            end = default_timer()
            print (b, counter)
            t()
            break

        else:

            counter += 1
            print (b,counter)
            x = b