A few notes:
A more pythonic way to determine if a given value is a palindrome:
str(n) == str(n)[::-1]You do something similar in your code, but are converting from a
stringback to anint. This is more readable to me.
However, this can slow down the code if we do this sort of casting a lot, so it would be better to abstract this functionality to a loop to reduce the number of casts and further increase readablity:
def is_palindrome(num):
string = str(num)
return string == string[::-1]
Use the palindrome test as a check with the
whileloopIn the while loop, use the logic you already have to add on a reversed
int:n += int(str(n)[::-1])I would make it easier to input a number for the code to use, I did this with
argparse.def get_args(): parser = argparse.ArgumentParser(description= 'Generate palindrome from number when added to its reverse') parser.add_argument('num', type=int, help='number for palindrome generator') return parser.parse_args()Right now you are writing just a snippet of data to a file, but it is being overwritten every time. I'd recommend just outputting to
stdoutwith this current method, or changing it so you append to a file instead of overwrite it. I've gone with the former recommendation in my final code.For profiling and timing code, it's recommended you use a Python profiler instead of writing code yourself.
Final Code
import argparse
def get_args():
parser = argparse.ArgumentParser(description=
'Generate palindrome from number when added to its reverse')
parser.add_argument('num', type=int, help='number for palindrome generator')
return parser.parse_args()
def is_palindrome(num):
string = str(num)
return string == string[::-1]
def main():
args = get_args()
while not is_palindrome(args.num):
args.num += int(str(args.num)[::-1])
print(return args.num)
if __name__ == "__main__":
print(main())
Test run:
$ python test.py 146
787