python - 在每次迭代中删除项目时测试数组时弹出索引超出范围
问题描述
我正在尝试解决几乎增加的序列问题。目标是查看一个数组是否是一个严格递增的序列,如果不超过一个元素被删除。我正在尝试使用该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
解决方案
foo = [1, 2, 3]
while foo:
print(foo)
foo.pop()
输出:
[1, 2, 3]
3
[1, 2]
2
[1]
1
推荐阅读
- html - 如何垂直居中两个子元素?
- java - 如果这些线程从不修改同一个项目,是否可以从多个线程修改 ArrayList 中的项目?
- angular - Angular HighCharts 更新系列
- python - 使用 lambda 函数的 Python 列表排序
- python - Python:需要在箱线图中重叠实际数据
- emeditor - 在 EmEditor 中:如何对两列单元格(在同一行)中的值求和并将结果存储在第三列中?
- laravel - 如何获取当前模块名称 [nwidart/laravel-modules]
- sql-server - SQL server 使用表参数运行作业
- postgresql - 查询以获取 OS 进程(postmaster)并在 postgres 数据库中与之关联的查询
- python-3.x - 如何在 Python 程序中使用正确的程序打开文件(例如,使用 Blender 的“.blend”和使用 Chrome 的“.webloc”)?