[英]What's the difference between the two of the codes?
第二個顯示 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
的值后立即退出,就像您的第一個程序一樣。 因此,在設置answer
后需要break
一下。
您看到的錯誤消息是由於以下原因:總是執行第二個和第三個if
語句。 如果d
為空,則當第三個if
語句嘗試訪問第一個和最后一個元素時會出現范圍錯誤。 上一段中的修復 - 在answer = "Yes"
之后添加break
- 也將修復此錯誤,但通過將第三個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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.