0

I tried some basic optimizations, to cut down on the number of operations for the general euler problem #4:

def is_palindrome(num):
    return str(num) == str(num)[::-1]

def fn(n):
    max_palindrome = 1
    for x in range(n,1,-1):
        for y in range(n,x-1,-1):
            if is_palindrome(x*y) and x*y > max_palindrome:
                max_palindrome = x*y
            elif x * y < max_palindrome:
                break
    return max_palindrome

print fn(999)

Can I/how do I optimize this further? (assume it's the general solution, for factors of at most n rather than at most 999).

AstroCB
  • 12,337
  • 20
  • 57
  • 73
blueberryfields
  • 45,910
  • 28
  • 89
  • 168
  • 1
    I assumed you have seen this answer: http://stackoverflow.com/a/12674588/895932 So what you want is a change to your code or what? – justhalf Sep 26 '13 at 09:35
  • yes - i'm doing these exercises to level up my python-fu, and looking for feedback on how to make my code, faster – blueberryfields Sep 26 '13 at 17:58
  • 1
    Aside: if you're looking for comments to improve working code, you should check out [codereview](http://codereview.stackexchange.com). – DSM Sep 26 '13 at 18:03

1 Answers1

1

Some small optimizations: you can break out early of the x-loop and reduce the number of calls to is_palindrome by swapping the checks around a bit (untested):

def fn(n):
    max_palindrome = 1
    for x in range(n,1,-1):
        if x * n <= max_palindrome: # nothing bigger possible for remaining x
            break
        for y in range(n,x-1,-1):
            if x * y <= max_palindrome: #nothing bigger possible for current x
                break
            if is_palindrome(x*y):
                max_palindrome = x*y
    return max_palindrome
Bas Swinckels
  • 18,095
  • 3
  • 45
  • 62