2 回答

TA贡献1836条经验 获得超3个赞
您需要强制转换为字符串才能反转和比较:
def largest_palindrome(): # <-- arguments are not needed
for y in (x for x in range(9801, 100, -1)): # use a generator, that iterates from largest to smallest.
if str(y) == str(y)[::-1]:
return y # early exit when largest match is found (it will be the first)
print(largest_palindrome())
扰流板警报:
9779
作为一个班轮:
max([x for x in range(9801, 100, -1) if str(x) == str(x)[::-1]])
作为一台班轮发电机
(感谢@Austin的评论):
next(x for x in range(9801, 100, -1) if str(x) == str(x)[::-1])

TA贡献1862条经验 获得超6个赞
Reblochon的答案不能解决问题,因为它只能在可能来自两个两位数的数字的最小和最大数字之间进行迭代。它不会遍历两位数的数字。
def largest_palindrome():
lastBiggestProduct = 0;
lastBiggestNumb = 10;
for firstNum in range(10,100):
a = list(range(lastBiggestNumb,firstNum))
a.extend(range(firstNum+1,100))
for secondNum in a:
prod = firstNum*secondNum
if(prod>lastBiggestProduct and str(prod) == str(prod)[::-1]):
lastBiggestProduct = firstNum*secondNum
lastBiggestNumb = secondNum
return lastBiggestProduct
print(largest_palindrome())
返回:
9009
添加回答
举报