2013-02-09 207 views
0

我試圖找到兩個3位數的乘積的最大回文。我的客人是迴文的形式爲abccba,所以我會循環每個數字,並停在最大的數字,這是兩個3位數字的乘積。Python中的嵌套循環

這段代碼

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,這是正確的。

我不知道我出錯的地方。

+0

通過考慮以下事實,可以高度簡化算法:任何迴文數都可以被「11」整除。因此,從最高倍數'11'開始,它是兩個3位數字的倍數,然後使用'xrange'中的'-11'並檢查數字是否是迴文。 – 2013-02-09 09:30:11

+0

謝謝。我提供了答案,所以他們給了我一個解決方案。我現在正在閱讀它,它也表明你提到了什麼。 – 2013-02-09 09:34:15

回答

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

xrange(start, stop, step)生成從start至(但不包括)stop,具有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爲好。

+0

謝謝。那麼我怎麼能用xrange()來限制從1到9的範圍呢? – 2013-02-09 09:14:08

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