![](/img/trans.png)
[英]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.