首页 > 解决方案 > Python,while循环在一次迭代后停止

问题描述

当程序接收到“立方体”的输入时,我想首先检查最大值是否在序列的一端。如果是,则删除最大值,如果不是,则退出并打印否。只要 'd' 不为空,就继续循环,直到 'd' 为空。然后打印是,或者在其中一个循环中退出程序。

我可以输入“T”个测试序列。假设我给出一个序列 [4, 3 ,1, 3 ,4]。它只进行一次迭代,但它应该继续并删除4、3、3、1。谢谢你的帮助!我有点不是很有经验。

from collections import deque
T=int(input())#number of test cases

for i in range(T):
    n=int(input())
    cubes=map(int, input().split())
    d=deque(cubes)       
    while len(d)!=0:
        a=max(d)
        if d.index(a)==0 or d.index(a)==-1:
            d.remove(a)
        else:
            break
            
     if len(d)==0:
         print('yes')
     else:
         print ('no')

标签: pythondebuggingwhile-loopiterationbreak

解决方案


我认为您在这里比较了错误的索引:

if d.index(a)==0 or d.index(a)==-1:

如果元素是最后一个,则返回 index len(d) - 1,而不是-1
https://docs.python.org/3/library/collections.html#collections.deque.index

你应该写这样的东西:

if d.index(a) == 0 or d.index(a) == len(d)-1:

推荐阅读