查找由两个2位数的乘积组成的最大回文

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    

最大回文率(100,9801)


当我执行此代码时,出现的错误是TypeError:'int'对象不可下标。我需要知道此代码中的问题是什么,以及将进行哪些更改以使此代码运行。


料青山看我应如是
浏览 161回答 2
2回答

米脂

您需要强制转换为字符串才能反转和比较:def largest_palindrome():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # <-- arguments are not needed&nbsp; &nbsp; for y in (x for x in range(9801, 100, -1)):&nbsp; # use a generator, that iterates from largest to smallest.&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if str(y) == str(y)[::-1]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return y&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 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():&nbsp; &nbsp; lastBiggestProduct = 0;&nbsp; &nbsp; lastBiggestNumb = 10;&nbsp; &nbsp; for firstNum in range(10,100):&nbsp; &nbsp; &nbsp; &nbsp; a = list(range(lastBiggestNumb,firstNum))&nbsp; &nbsp; &nbsp; &nbsp; a.extend(range(firstNum+1,100))&nbsp; &nbsp; &nbsp; &nbsp; for secondNum in a:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; prod = firstNum*secondNum&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(prod>lastBiggestProduct and str(prod) == str(prod)[::-1]):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lastBiggestProduct = firstNum*secondNum&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lastBiggestNumb = secondNum&nbsp; &nbsp; return lastBiggestProductprint(largest_palindrome())返回:9009
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python