Python中的嵌套循环

时间:2013-02-09 09:11:35

标签: python

我正在努力寻找最大的回文,它是两个3位数字的乘积。我的客人是回文将具有abccba形式,所以我将遍历每个数字并停在最大数字处,这是两个3位数字的乘积。

这段代码

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

产生888888 = 962 * 924,这是不正确的。


此代码

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

产生906609 = 993 * 913,这是正确的。

我不知道哪里出错了。

2 个答案:

答案 0 :(得分:4)

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

xrange(start, stop, step)生成startstop但不包括step的所有数字,步骤为xrange(5) == (0, 1, 2, 3, 4) xrange(1, 5) == (1, 2, 3, 4) xrange(1, 5, 2) == (1, 3)

xrange(1, 10)

您也可以9在该范围内加入{{1}}。

答案 1 :(得分:2)

只有(大约)50万对3位数字,所以测试它们的速度更快更简单。

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