Problem 55

completed December 24, 2011

Comments

The hardest part of this one was defining functions that find the palindrome of a number and then add it to the original. It took a little work with string methods, but all in all, it wasn’t too bad. To get the reversed order of a number, I used a for loop that then took the numbers in reverse order from the original and fed them into a new number.

Code

def ispalindrome(n):
	number = str(n)
	backward = [[]] * len(number)
	for i in range(len(number)):
		backward[len(number) - i - 1] = number[i]
	backward = ''.join(map(str, backward))
	if backward == number: return True
	else: return False


def reverse_and_add(n):
	number = str(n)
	backward = [[]] * len(number)
	for i in range(len(number)):
		backward[len(number) - i - 1] = number[i]
	backward = ''.join(map(str, backward))
	number = int(number)
	backward = int(backward)
	return number + backward

Lychrel = 0

for n in range(10000):
	for x in range(50):
		n = reverse_and_add(n)
		if ispalindrome(n) == True:
			break
			break
	else:
		Lychrel += 1
		
print Lychrel