Lim H.
Lim H.

Reputation: 10050

Nested Loop in Python

I'm trying to find the largest palindrome that is the product of two 3-digit numbers. My guest is that the palindrome will have the form abccba, so I will just loop over each digit and stop at the largest number that is the product of two 3-digit numbers.

This piece of code

def hasLargeDivisors(n):
    """
    Function to determine if a number has two divisors
    greater than 99
    """
    d = 999
    while n / d > 99 and n / d < 999 and d > 99:
        if n % d is 0:
            return True
        d-=1

    return False

def compisitePalindrome():
    """
    Function to find the largest palindrome 
    that is the product of 2 three-digit numbers
    """ 
    for a in reversed(xrange(1, 9)):
        for b in reversed(xrange(0, 9)):
            for c in reversed(xrange(0, 9)):
                num = a*100001 + b*10010 + c*1100
                if hasLargeDivisors(num):
                    return num

    return 0

produces 888888 = 962 * 924, which is incorrect.


This code

def hasLargeDivisors(n):
    """
    Function to determine if a number has two divisors
    greater than 99
    """
    d = 999
    while n / d > 99 and n / d < 999 and d > 99:
        if n % d is 0:
            return True
        d-=1

    return False

def compisitePalindrome():
    """
    Function to find the largest palindrome 
    that is the product of 2 three-digit numbers
    """ 
    a = 9
    for b in reversed(xrange(0, 9)):
        for c in reversed(xrange(0, 9)):
            num = a*100001 + b*10010 + c*1100
            if hasLargeDivisors(num):
                return num

    return 0

produces 906609 = 993 * 913, which is correct.

I don't know where I went wrong.

Upvotes: 0

Views: 116

Answers (2)

Paul Hankin
Paul Hankin

Reputation: 58241

There's only (approximately) half a million pairs of 3-digit numbers, so it's quicker and simpler to test them all.

def palindrome_3products():
    for i in xrange(100, 1000):
        for j in xrange(i, 1000):
            if str(i * j) == str(i * j)[::-1]:
                yield i * j, i, j

print max(palindrome_3products())

Upvotes: 2

Volatility
Volatility

Reputation: 32300

xrange(1, 9) == (1, 2, 3, 4, 5, 6, 7, 8)

xrange(start, stop, step) generates all numbers from start to (but not including) stop, with a step of step.

xrange(5) == (0, 1, 2, 3, 4)
xrange(1, 5) == (1, 2, 3, 4)
xrange(1, 5, 2) == (1, 3)

You can do xrange(1, 10) to include 9 in the range as well.

Upvotes: 4

Related Questions