[英]What differs in while and for loops?
這是來自Kaggle的問題。
我嘗試使用 while 循環,但我想我在這里遺漏了一些基本的東西。
使用while循環的注釋代碼是我的開始,未注釋的代碼是解決方案。 網站上給出的詳細解決方案粘貼如下:
def menu_is_boring(meals):
"""Given a list of meals served over some period of time, return True if the
same meal has ever been served two days in a row, and False otherwise.
"""
# i = 1
# while (i) < (len(meals)-1) :
# if meals[i] == meals[i+1] :
# return True
# else :
# i = i + 1
# return False
for i in range(len(meals)-1):
if meals[i] == meals[i+1]:
return True
return False
# Check your answer
q3.check()
我們解決方案的關鍵是調用范圍。 range(len(meals)) 會給我們所有的膳食指數。 如果我們使用了那個范圍,循環的最后一次迭代將比較最后一個元素和它后面的元素,這是……IndexError。 range(len(meals)-1) 為我們提供了除最后一個元素的索引之外的所有索引。
但是我們不需要檢查 meals 是否是空的嗎? 結果是 range(0) == range(-1) - 它們都是空的。 因此,如果 meals 的長度為 0 或 1,我們就不會對 for 循環進行任何迭代。
您可以簡單地使用內置的 function any()
def menu_is_boring(meals):
return any(meals[i] == meals[i+1] for i in range(len(meals)-1))
While 和 For 循環的區別很簡單:
break
它們或通過特定條件break
它們時。for 循環不能永遠運行,但 while 循環可以。
for和while循環的區別:
for 循環用於在容器和/或數據流(例如列表)上循環或迭代,並且要對該數據完成的任務的持續時間通常由所述容器中的數據量或 stream 決定。
while 循環用於循環或重復任務通常不確定的次數,並且要完成的任務的持續時間是通過滿足通常與初始數據量無關的某些條件來確定的。
while 循環是兩者中更通用的一種,實際上您可以用 while 循環完成 for 循環所做的一切,但這樣做更容易出錯,因為您需要跟蹤 for-循環照顧你喜歡索引。
關於您的示例代碼,您的 while 循環版本的唯一問題是您以 1 而不是 0 開始索引(列表索引在 python 中從 0 開始)。
而且你的 for-loop 版本沒有什么特別的錯誤,有一些方法可以做到這一點,這樣你就不需要跟蹤任何索引,比如
for a, b in zip(meals, meals[1:]): # using the zip function along with using the slice notation in order to pair the first element with second...
if a == b:
return True
return False
from itertools import pairwise # python 3.10+
for a, b in pairwise(meals): # using the pairwise function to pair the first element with second...
if a == b:
return True
return False
(或他們的一個班輪版本......)
也許你可以試試:
i = 1
while False :
if meals[i] == meals[i+1] :
return True
else :
i = i + 1
return False
但你可以無限循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.