在python中从3个数字的乘积中找到最大的回文

2024-06-09 20:37:27 发布

您现在位置: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

Tags: theinfromforisrevrangeproduct
3条回答

n == a永远不会是True,因为k = str(t)[::-1](即a)是字符串,而t = i*jn是整数。尝试:

a = int(k)

两个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

问题已经得到了回答,这里有一点优化:

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

相关问题 更多 >