Optimizing Project Euler 36 - double-base palindromes This one was quick and simple. Any optimizations?

from timeit import default_timer as timer

def sum_double_base_palindromes_under(limit):
    def is_palindrome(n):
        if str(n) == str(n)[::-1]:
            return True
        return False
    sum = 0
    for n in range(limit):
        if is_palindrome(n) and is_palindrome(int(bin(n)[2:])):
            sum += n
    return sum

start = timer()
ans = sum_double_base_palindromes_under(1000000)
elapsed_time = (timer() - start) * 1000 # s --&gt; ms

print "Found %d in %r ms." % (ans, elapsed_time)
In any programming language, I'd consider (assuming c is a condition with a boolean value):

if c:
    return True
else:
    return False


or it's equivalent :

if c:
    return True
return False


to be an anti-pattern that should be written:

return c




Your for loop can easily be rewritten into a more concise (and more efficient according to my benchmarks) way using sum :

return sum(n for n in range(limit) if is_palindrome(n) and is_palindrome(int(bin(n)[2:])))




An easy optimisation is not to compute str(n) more than needed :

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


Also, it might even be faster to feed strings to your functions :

def is_palindrome(s):
    return s == s[::-1]
return sum(n for n in range(limit) if is_palindrome(str(n)) and is_palindrome(bin(n)[2:]))


On my machine, running your function 10 times, the running time went from 470 ms to 310 ms per iterations.