簡體   English   中英

從python中3個數字的乘積中找到最大的回文

[英]find the largest palindrome from the product of 3 numbers in python

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

from sys import exit
rev=0
print ' let us start'
for i in range(999,100,-1):
    for j in range(999,100,-1):
        product = i*j
        temp = product 
        rev1 = str(product)[::-1]
        a = rev1
        if temp == a:

            print ' is a palindrome'
            if a > rev:
            rev = a
            c = temp
            h = i
            y = j

print '%r*%r=%r,which is the highest palindrome %r' % ( h, y, c, rev)
print a         
print rev1
print temp
print 'over'

輸出:我正在使用sublime text2作為編輯器

let us start
Traceback (most recent call last):
      File "palindrome.py", line 19, in <module>
        print '%r*%r=%r,which is the hghest palindrome %r' % ( h, y, c, l)
    NameError: name 'h' is not defined

n == a永遠不會是True ,因為k = str(t)[::-1] (即a )是一個字符串,而t = i*jn是一個整數。 嘗試:

a = int(k)

雖然問題已經得到回答,但是這里有些優化:

>>> largest, loopmax = -1, -1
>>> largest_t = (0,0)
>>> for i in range(999,100,-1):
        for j in range(999,100,-1):
            p = i*j
            n = str(p)
            if n == n[::-1]:
                loopmax = p
                break # no need to loop further as j decreases and can never be any greater

        if loopmax > largest:
            largest = loopmax
            largest_t = (i,j)

        if i<largest_t[1]: 
            break # further looping will generate only lower palindromes.


>>> largest
906609
>>> largest_t
(993, 913)

少於100萬個具有兩個3位數數字的產品,因此采用蠻力方法可以找到最大的(按數字表示)也是回文的產品:

all3digit = range(100, 1000) # all 3-digit numbers
products = (x*y for x in all3digit for y in all3digit)

def ispalindrome(p):
    s = str(p)
    return s == s[::-1]

print(max(filter(ispalindrome, products))) # -> 906609

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM