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

如何只打印此输出的最后一行?

如何只打印此输出的最后一行?

LEATH 2023-08-03 17:30:14
我需要找到 10000 以下的最长的非素数行。如何仅打印输出中的最后一行?没有 max 函数,也没有简单的数值约束。我认为它只需要一些小的调整,只是不知道在哪里或如何调整。priemen = []for x in range(2,10000):    #prime generator    tel = 0    for deler in range(1,x):        if x % deler == 0:            tel += x % deler == 0    if tel <2:        priemen.append(x)   a = priemen[0]b = priemen[1]maxrow = 0for next in priemen[2:]:        a = b    b = next    row = b - a - 1               if row > maxrow:        maxrow = row        print("The longest row starts at", a+1, "and stops at", b-1, "and is", maxrow, "long.")------------------Output: The longest row starts at 8 and stops at 10 and is 3 long.The longest row starts at 24 and stops at 28 and is 5 long.The longest row starts at 90 and stops at 96 and is 7 long.The longest row starts at 114 and stops at 126 and is 13 long.The longest row starts at 524 and stops at 540 and is 17 long.The longest row starts at 888 and stops at 906 and is 19 long.The longest row starts at 1130 and stops at 1150 and is 21 long.The longest row starts at 1328 and stops at 1360 and is 33 long.The longest row starts at 9552 and stops at 9586 and is 35 long.我只需要它来打印最后一张
查看完整描述

2 回答

?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

您需要将a和的值保存b到单独的变量中,以便可以在循环后打印它们。


b = priemen[1]

maxrow = 0


for n in priemen[2:]:

    a = b

    b = n

    row = b - a - 1       

    

    if row > maxrow:

        maxrow = row

        a_max = a

        b_max = b


if maxrow != 0:

    print("The longest row starts at", a_max + 1, "and stops at", b_max - 1, "and is", maxrow, "long.")

其他注意事项:

  • a_max我还没有初始化b_max- 但最终的if测试是为了防止任何尚未设置的情况

  • 我已重命名nextn,因为next这是内置名称

  • a = priemen[0]行毫无意义,所以我已将其删除



查看完整回答
反对 回复 2023-08-03
?
动漫人物

TA贡献1815条经验 获得超10个赞

我发现这段代码效率低下并且存在问题。首先,它的效率很低,因为它测试从 1 到x


for deler in range(1, x):

当它只需要测试从 3 到的平方根的奇数除数(处理偶数之后)时。但即使这样也是低效的,因为它正在创建一个素数列表,它可以用作除数来进一步加快速度!最后,就效率而言,我相信它可以一次性完成:x


TARGET = 10_000  # below this number


primes = [2]


start = end = primes[-1]


for number in range(3, TARGET, 2):


    def is_prime(number):

        for divisor in primes:

            if divisor * divisor > number:

                return True


            if number % divisor == 0:

                return False


        return True


    if is_prime(number):

        primes.append(number)


        if primes[-1] - primes[-2] > end - start:

            start, end = primes[-2:]


print("The longest run starts at", start + 1, "and stops at", end - 1, "and is", end - start - 1, "long.\n")

最后,就目标而言,问题未明确说明,并且解决方案可能是错误的。考虑目标为 9586 而不是 10000。编写的代码将打印:


The longest run starts at 1328 and stops at 1360 and is 33 long.

但是通过在主循环之后添加以下代码:


if TARGET - primes[-1] > end - start:

    start, end = primes[-1], TARGET

我们得到正确答案:


The longest run starts at 9552 and stops at 9585 and is 34 long.

如果目标更大,跑步会更长,但这仍然是最长的跑步。


查看完整回答
反对 回复 2023-08-03
  • 2 回答
  • 0 关注
  • 93 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信