为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

料青山看我应如是 2021-05-12 18:19:54
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'对象不可下标。我需要知道此代码中的问题是什么,以及将进行哪些更改以使此代码运行。
查看完整描述

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])


查看完整回答
反对 回复 2021-05-25
?
阿波罗的战车

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


查看完整回答
反对 回复 2021-05-25
  • 2 回答
  • 0 关注
  • 160 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号