在python中从3个数字的乘积中查找最大回文
输出:我使用升华文本2作为编辑器在python中从3个数字的乘积中查找最大回文,python,Python,输出:我使用升华文本2作为编辑器 #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
#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'
让我们开始吧
回溯(最近一次呼叫最后一次):
文件“palindrome.py”,第19行,在
打印“%r*%r=%r,这是最高回文%r%”(h、y、c、l)
NameError:未定义名称“h”
n==a
永远不会是True
,因为k=str(t)[::-1]
(即a
)是字符串,而t=i*j
即n
是整数。尝试:
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
问题已经得到了回答,这里有一点优化:
a = int(k)
>最大,loopmax=-1,-1
>>>最大值t=(0,0)
>>>对于范围(999100,-1)内的i:
对于范围(999100,-1)内的j:
p=i*j
n=str(p)
如果n==n[:-1]:
loopmax=p
break#当j减小时,无需进一步循环,并且永远不会更大
如果loopmax>最大值:
最大=最大
最大值t=(i,j)
如果我>>最大
906609
>>>最大的
(993, 913)
两个3位数字的乘积不到一百万,因此蛮力方法可以找到最大的(数字)也是回文的乘积:
>>> 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)
你应该考虑更详细地命名你的变量!好的,谢谢你的建议汉克斯,这很有用,但我仍然没有得到所需的output@user3396137然后编辑您的问题,告诉其他人您需要的输出是什么以及您现在得到了什么;)谢谢,我知道了,我是初学者。我能知道问题中的错误吗
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