python - 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')
解决方案
我认为您在这里比较了错误的索引:
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:
推荐阅读
- android - 在所有其他 Android 应用之上显示应用视图
- java - Apache POI - 将样式从 XSSFCell 复制到 HSSFCell
- ember.js - Ember.js 和图片上传
- android - 使用 Duktape Android 在 kotlin 中运行 rxjs 返回 SyntaxError
- java - 无法连接两个对象
- docker - 使用 google-stackdriver 监控 Nginx 和 Docker
- wordpress - 在不更改布局的情况下显示特定类别的帖子
- python - 如何在单个列表中合并列表值?
- asp.net - web.api 中的处理程序路由
- java - 如何启动 FlutterActivity 并更改路由