Project Euler – Problem # 36 – Solved with Python

Problem:

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.)

One Possible Solution:

# Python version = 2.7.1
# Platform = win32

def binary_rep(i):
    """Take decimal i and convert to binary with
    built in function bin, slice off first two
    characters."""
    x = bin(i)
    y = x[2:]
    return y

def reverse_binary(y):
    """Take binary number y and reverse characters"""
    x = y[::-1]
    return x

def reverse_decimal(i):
    """Take decimal number i and reverse characters"""
    y = str(i)
    d = y[::-1]
    return d

def main():
    """Main Program"""
    L = []
    Answer = 0
    for i in range(1, 1000000):
        x = binary_rep(i)
        y = reverse_binary(x)
        if x == y:
            a = int(reverse_decimal(i))
            if i == a:
                L.append(i)
        else:
            continue
    Answer = sum(L)
    print "Sum = ", Answer
        
if __name__ == '__main__':
    main()
Advertisements

One Reply to “Project Euler – Problem # 36 – Solved with Python”

  1. well…

    sum = 0
    for i in range(1000000):
    if str(i) == str(i)[::-1] and “{0:0b}”.format(i) == “{0:0b}”.format(i)[::-1]:
    sum+=i
    print sum

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.