I suspect the reason that the code checks for x*y < max_seen
first is that it is an easier test than is_palindrome
. If you expect many of your potential x
and y
values to be no good, it makes sense to do the easiest tests first so that you only need to run the complicated tests a few times.
That said, if x*y < max_seen
is true, there won't be any successful tests for the current x
value. An optimization could be to replace continue
(which goes on to the next y
value) with break
(which ends the inner loop and so goes on to the next x
value).
You could even do something similar for the outer loop, and test if x * 999 < max_seen
. If so, you'll never find a better result and you can stop looping. Here's how that would look in code:
def biggest():
big_x, big_y, max_seen = 0, 0, 0
for x in xrange(999,99,-1):
if x*x < max_seen:
break # breaks out of outer loop, as no later x value can be better
for y in xrange(x, 99,-1):
if x*y < max_seen:
break # breaks out of inner loop, no later y value can be better
if is_palindrome(x*y):
big_x, big_y, max_seen = x,y, x*y
return big_x, big_y, max_seen