首页 > 解决方案 > 这两个代码有什么区别?

问题描述


第二个显示 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

标签: pythonfunctiondebugging

解决方案


在您的第一个程序中:

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"明确意图不会有什么坏处,因此它仅在非空时执行。ifelifd

最后,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)

推荐阅读