[FINAL SOLUTION] Lychrel Numbers
The previous solution was already almost correct. The only change we need to do is in the is_lychrel method. We change this (wrong) code:
def is_lychrel(number, invocation): if invocation > MAX_ITERATIONS: return True if is_palindrome(number): return False return is_lychrel(number + int(reverse_number(number)), invocation + 1)
to
def is_lychrel(number, invocation): if invocation > MAX_ITERATIONS: return True result = number + int(reverse_number(number)) if is_palindrome(result): return False return is_lychrel(result, invocation + 1)
The change really is that we no longer check is_palindrome on the input number but rather on the result of the calculation.
The complete and correct solution looks like this:
#!/usr/bin/env python MAX_ITERATIONS = 50 NRS_TO_CHECK = 10000 def reverse_number(number): return str(number)[::-1] def is_palindrome(number): nr_as_string = str(number) reverse_as_string = reverse_number(number) return str(number) == reverse_as_string def is_lychrel(number, invocation): if invocation > MAX_ITERATIONS: return True result = number + int(reverse_number(number)) if is_palindrome(result): return False return is_lychrel(result, invocation + 1) lychrel_numbers = 0 for cur_number in range(1, NRS_TO_CHECK): if is_lychrel(cur_number, 0): lychrel_numbers += 1 if is_palindrome(cur_number): print 'is lychrel and initial palindrome: ' + str(cur_number) print 'Lychrel numbers below {0}: {1}'.format(NRS_TO_CHECK, lychrel_numbers)
Running this code now returns the correct result
Lychrel numbers below 10000: 249
If you made it this far, well done and thank you for sticking around. Feel free to leave any questions by leaving a comment and we will get back to you.
Lynx