python - 这两个代码有什么区别?
问题描述
第二个显示 IndexError: deque index out of range 而另一个完美运行,有人可以解释一下吗?输出只能是“是”或“否”。
from collections import deque
def check(d):
while d:
big = d.popleft() if d[0]>d[-1] else d.pop()
if not d:
return "Yes"
if d[-1]>big or d[0]>big:
return "No"
for i in range(int(input())):
int(input())
d = deque(map(int,input().split()))
print(check(d))
from collections import deque
for i in range(int(input())):
int(input())
numbers = list(map(int, input().split()))
d = deque(numbers)
n = len(numbers)
while d:
if d[0]>d[-1]:
previous = d.popleft()
else:
previous = d.pop()
if not d:
answer = "Yes"
if d[-1]>previous or d[0]>previous:
answer = "No"
print(answer)
样本输入:
2
6
4 3 2 1 3 4
3
1 3 2
解决方案
在您的第一个程序中:
while d:
big = d.popleft() if d[0]>d[-1] else d.pop()
if not d:
return "Yes"
if d[-1]>big or d[0]>big:
return "No"
当return
双端队列为空或第一个或最后一个元素大于刚刚弹出的元素时,将退出循环。
但是在你的第二个程序中:
while d:
if d[0]>d[-1]:
previous = d.popleft()
else:
previous = d.pop()
if not d:
answer = "Yes"
if d[-1]>previous or d[0]>previous:
answer = "No"
在双端队列为空之前不会退出循环,但是您希望在确定 的值后立即退出answer
,就像您的第一个程序一样。所以需要有一个break
刚刚answer
设置。
您看到的错误消息是由于以下原因:if
总是执行第二条和第三条语句。如果为空,则在第三条语句尝试访问第一个和最后一个元素d
时会出现范围错误。if
上一段中的修复 - 添加break
之后- 也将修复此错误,但通过将第三个更改为来answer = "Yes"
明确意图不会有什么坏处,因此它仅在非空时执行。if
elif
d
最后,print(answer)
应该在循环的外部,而不是内部。
这是第二个程序的固定版本:
from collections import deque
for i in range(int(input())):
int(input())
numbers = list(map(int, input().split()))
d = deque(numbers)
n = len(numbers)
while d:
if d[0]>d[-1]:
previous = d.popleft()
else:
previous = d.pop()
if not d:
answer = "Yes"
break
elif d[-1]>previous or d[0]>previous:
answer = "No"
break
print(answer)
推荐阅读
- python - 当某些输入被命名而其他输入没有被命名时,如何在 python 中使用(或打开)args?
- javascript - 在 for 循环的每次迭代中输出一个数组
- python - 如何检测已经在 Python 中按字母顺序排序的文本文件内容
- r - R Notebook 和 knitr 与乳胶桌?
- python - 如何在继承的实例之间共享类变量?
- listbox - 当前的 Julia Gtk.jl 包中没有实现 GtkListbox 吗?
- r - 有没有办法引用特定的代码
- visual-studio-code - 路径指向版本 0 时需要 JDK 8+
- c++ - How to pass a reference of template reference into class method?
- c# - C# - How to obtain 'Alias' of application hosted inside a website in IIS?