continue - Euler #4 in Python -


a palindromic number reads same both ways. largest palindrome made product of 2 2-digit numbers 9009 = 91 × 99.
find largest palindrome made product of 2 3-digit numbers.

http://projecteuler.net/problem=4

below solution problem. works, noticed solution used

if x*y < max_seen: continue 

like this:

def biggest():     big_x, big_y, max_seen = 0, 0, 0     x in xrange(999,99,-1):         y in xrange(x, 99,-1):              if x*y < max_seen: continue             if is_palindrome(x*y):                 big_x, big_y, max_seen = x,y, x*y 

what don't how line works. first time through max_seen = 0 , first x*y 999*999 greater 0. condition isn't met , next line run. makes sense. eventually, however, max_seen larger x*y why continue here?

it seems line isn't needed because if condition or isn't met program continue anyway. suspect i'm not understanding how continue works in python.

this approach:

def find_biggest():     big_x, big_y, new_pal, max_seen = 0, 0, 0, 0     x in range(999, 100, -1):         y in range(x, 100, -1):             if is_palindrome(x*y) == true:                 new_pal = x*y                 if new_pal > max_seen:                     big_x, big_y, max_seen = x, y, new_pal 

from efficiency standpoint program should exit new x*y < max_seen, 999*100 less 998*900 (meaning couldn't stop yet still needs check 998*y, 997*y, etc.) how code that?

i suspect reason code checks x*y < max_seen first is easier test is_palindrome. if expect many of potential x , y values no good, makes sense easiest tests first need run complicated tests few times.

that said, if x*y < max_seen true, there won't successful tests current x value. optimization replace continue (which goes on next y value) break (which ends inner loop , goes on next x value).

you similar outer loop, , test if x * 999 < max_seen. if so, you'll never find better result , can stop looping. here's how in code:

def biggest():     big_x, big_y, max_seen = 0, 0, 0     x in xrange(999,99,-1):         if x*x < max_seen:             break # breaks out of outer loop, no later x value can better         y in xrange(x, 99,-1):              if x*y < max_seen:                 break # breaks out of inner loop, no later y value can better             if is_palindrome(x*y):                 big_x, big_y, max_seen = x,y, x*y     return big_x, big_y, max_seen 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -