sum67:为什么“超时”?

2024-05-15 01:29:06 发布

您现在位置:Python中文网/ 问答频道 /正文

对于codebat中的“sum67”python练习,我的所有结果都返回一个“超时”结果。尽管如此,当我在空闲状态下运行代码时,它似乎工作得很好。你知道吗

在练习中,我必须返回列表中所有nums的总和。但是6和7之间的nums,包括在内,不能算数。你知道吗

有人能帮我找出原因吗?我要死了

def sum67(nums):
    count = 0
    while 6 in nums: 
        place_6 = nums.index(6)
        place_7 = nums.index(7)+1
        del nums[place_6:place_7]
    for i in nums:
        count += i
    return count

非常感谢:D


Tags: 代码in列表index状态defcountplace
3条回答

您的解决方案工作得很好,所以我认为CodingBat有一个非常不可原谅的超时阈值!是他们,不是你。你知道吗

您将得到一个timeout error,因为while <int> in <array>将一直返回true,直到您在while循环条件中编辑要测试的对象。你知道吗

您的代码失败的原因是因为您假设对于每一个6,后面也会有一个7,而事实可能并非如此。你知道吗

发生这种情况时,您的代码可以:

  • no7存在时引发ValueError(请尝试[1, 6, 2]),或
  • 如果7确实存在,但在6之前,则会超时(切片无法从list中删除任何内容,但无论如何您会反复尝试..)(请尝试使用[1, 7, 6, 2]

不如这样吧:

def sum67(nums):
    stop = False
    count = 0
    for number in nums:
        if number == 6:
            stop = True
        elif stop and number == 7:
            stop = False
        else:
            if not stop:
                count += number
    return count

您只需继续添加术语,除非遇到6。如果这样做,则停止添加,直到找到7。你知道吗

请注意,这肯定是可以改进的。这是一种快速而肮脏的解决方案,尽管如此。你知道吗

相关问题 更多 >

    热门问题