[英]Find the largest palindrome made from the product of two 3-digit numbers using numpy
[英]To find the largest palindrome made from the product of two 2-digit numbers
def largest_palindrome(n1,n2):
mylist = [x for x in range(n1,n2)]
for y in mylist:
if y == y[::-1]:
print(y)
else:
pass
large_palindrome(100,9801)
当我执行此代码时,出现的错误是TypeError: 'int' object is not subscriptable 。 我需要知道这段代码中的问题是什么,以及要进行哪些更改才能使这段代码运行。
您需要转换为字符串才能反转和比较:
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])
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.