Double-base palindromes

The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.

Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.

(Please note that the palindromic number, in either base, may not include leading zeros.)


Idea

Iterate and check if is palindrome in base 10 and base 2.

No leading zeros means no tailing zeros, so cannot be even number. (Even number has tailing zero in base 2).


In [1]:
def is_palindrome_base10(n):
    l = len(str(n))
    for i in range(l // 2):
        p = pow(10, l-2*i-1)
        if n % 10 != n // p:
            return False
        n = (n % p) // 10
    return True
In [2]:
is_palindrome_base10(1)
Out[2]:
True
In [3]:
is_palindrome_base10(585)
Out[3]:
True
In [4]:
is_palindrome_base10(123)
Out[4]:
False
In [5]:
def is_palindrome_base2(n):
    b = bin(n)[2:]
    half = len(b) // 2
    return n == 1 or b[:half] == ''.join(reversed(b[-half:]))
In [6]:
is_palindrome_base2(1)
Out[6]:
True
In [7]:
is_palindrome_base2(5)
Out[7]:
True
In [8]:
is_palindrome_base2(585)
Out[8]:
True
In [9]:
is_palindrome_base2(123)
Out[9]:
False
In [10]:
def is_doublebase_palindrome(n):
    if n % 2 == 0:
        return False
    return is_palindrome_base10(n) and is_palindrome_base2(n)
In [11]:
is_doublebase_palindrome(585)
Out[11]:
True
In [12]:
def solve(bound):
    doublebase_palindromes = list(filter(is_doublebase_palindrome, range(1, int(bound))))
    return sum(doublebase_palindromes), list(zip(doublebase_palindromes, map(lambda n: bin(n)[2:], doublebase_palindromes)))
In [13]:
solve(100)
Out[13]:
(157,
 [(1, '1'),
  (3, '11'),
  (5, '101'),
  (7, '111'),
  (9, '1001'),
  (33, '100001'),
  (99, '1100011')])
In [14]:
solve(1e6)
Out[14]:
(872187,
 [(1, '1'),
  (3, '11'),
  (5, '101'),
  (7, '111'),
  (9, '1001'),
  (33, '100001'),
  (99, '1100011'),
  (313, '100111001'),
  (585, '1001001001'),
  (717, '1011001101'),
  (7447, '1110100010111'),
  (9009, '10001100110001'),
  (15351, '11101111110111'),
  (32223, '111110111011111'),
  (39993, '1001110000111001'),
  (53235, '1100111111110011'),
  (53835, '1101001001001011'),
  (73737, '10010000000001001'),
  (585585, '10001110111101110001')])