首页 > 解决方案 > 在每次迭代中删除项目时测试数组时弹出索引超出范围

问题描述

我正在尝试解决几乎增加的序列问题。目标是查看一个数组是否是一个严格递增的序列,如果不超过一个元素被删除。我正在尝试使用该pop()方法来完成此操作。这是我到目前为止所拥有的:

def almostIncreasingSequence(sequence):
    new_seq = sequence

    output = False

    for i in range(len(sequence)):
        new_seq.pop(i)
        if all(i < j for i, j in zip(new_seq, new_seq[1:])):
            output = True
        else:
            output = False

    return output

我基本上是在索引 i 处弹出元素,然后output根据它是否严格增加而分配一个布尔值,但这是我得到的错误:

Traceback (most recent call last):
  main.py3 in the pre-written template, in getUserOutputs
    userOutput = _runmaxat(testInputs[i])
  main.py3 in the pre-written template, in _runmaxat
    return almostIncreasingSequence(*_fArgs_mksftvlwcpxn)
  main.py3 on line 6, in almostIncreasingSequence
    sequence.pop(i)
IndexError: pop index out of range
Sample tests: 0/19

标签: pythonarraysalgorithm

解决方案


foo = [1, 2, 3]
while foo:
    print(foo)
    foo.pop()

输出:

[1, 2, 3]
3
[1, 2]
2
[1]
1

推荐阅读