编码逻辑(Python)

Coding logic (Python)

我正在学习 python 课程,并且 运行 遇到了一个让我对逻辑有点困惑的问题。 问题是:

编写一个接受整数列表的函数,returns如果它按顺序包含 007,则为真:

spy_game([1,2,4,0,0,7,5]) --> True
spy_game([1,0,2,4,0,5,7]) --> True
spy_game([1,7,2,0,4,5,0]) --> False

这是我的解决方案:

def spy_game(nums):
    code = ["x",0,0,7] #"x" at index 0
    for i in nums:
        if i == code[1]: # check if i matches seq index 1
            code.pop(1) # if True, remove i at seq index 1
    return len(code) == 1

但是,此解决方案返回了一条错误消息:

IndexError                                Traceback (most recent call last)
<ipython-input-41-76ad0cd13e33> in <module>
      1 # Check
----> 2 spy_game([1,2,4,0,0,7,5])

<ipython-input-40-54389cdc3f5f> in spy_game(nums)
      2     code = ["x",0,0,7]
      3     for i in nums:
----> 4         if i == code[1]:
      5             code.pop(1)
      6     return len(code) == 1

IndexError: list index out of range

这是“正确”的解决方案:

def spy_game(nums):
    code = [0,0,7,"x"] # "x" placed at index 3 instead
    for i in nums:
        if i == code[0]: # check i against sequence index 0
            code.pop(0)
    return len(code) == 1

我无法理解为什么我的原始解决方案失败了。当列表的索引为 0-3 时,为什么索引 [1]“超出 运行ge”?我在逻辑中缺少什么?任何人都可以分解它吗?提前致谢。

你应该写下 code 每次迭代 for i in nums 后发生的情况。

你会发现,遇到0、0、7之后,nums可能还是不为空。 0、0 和 7 将从 code 中弹出,留下长度为 1 的列表,使 code[1] 在下一次迭代时抛出 IndexError。