Project Euler: Problem 4

Every now and then I do a Project Euler problem, mostly to build up my familiarity with Python. Below is my solution for problem 4.

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 ×99.

Find the largest palindrome made from the product of two 3-digit numbers.

#Palindrome.py
#Matt Rosenzweig
#Find the largest palindromic number made from the product of 3-digit numbers.

def palindrome():
    #Import the numpy package.
    import numpy as np

    #Products of three digit numbers are between 10000 and 1000000
    digits = range(100,999,1)
    products = np.outer(np.array(digits),np.array(digits))
    
    #Find all the palindromes between 10000 and 1000000
    rng = range(10000,1000000,1)
    #Initialize palindrome list.
    palindrome = []
    
    #Test each number between 10000 and 1000000 to see if its a palindrome
    for i in rng:
        #If a number is palindromic, then append it to the palindrome list.
        if str(i) == str(i)[::-1]:
            palindrome.append(i)

    #Convert the list palindrome to an array
    palindrome = np.array(palindrome)

    #Find the intersection of the arrays palindrome and products
    prod_palindrome = np.intersect1d(palindrome,products)

    #Return the largest palindrome which is the product of two three-digit numbers
    return np.amax(prod_palindrome)
        
Advertisements
This entry was posted in cs.DS, Python and tagged , . Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s