[英]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
largest_palindrome(100,9801) large_palindrome(100,9801)
When I am executing this code the error that comes up is TypeError: 'int' object is not subscriptable .当我执行此代码时,出现的错误是TypeError: 'int' object is not subscriptable 。 I need to know what is the problem is in this code and what changes will be done to make this code running.我需要知道这段代码中的问题是什么,以及要进行哪些更改才能使这段代码运行。
You need to cast to string to be able to reverse and compare:您需要转换为字符串才能反转和比较:
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]])
(thanks @Austin in the comments): (感谢@Austin 在评论中):
next(x for x in range(9801, 100, -1) if str(x) == str(x)[::-1])
Reblochon's answer doesn't solve the problem as it only iterates between the smallest and the biggest number that could come from two two-digit numbers. Reblochon 的答案并没有解决问题,因为它只在可能来自两个两位数的最小和最大数字之间进行迭代。 It doesn,t iterate through two-digit numbers.它不会遍历两位数。
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())
That returns:那返回:
9009
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.