[英]Finding best combinations of consecutive and same numbers in a list starting with a group of at least 3
[英]Recursively finding the same numbers in a list
我一直想練習我的 python,所以我希望能夠使用遞歸找到數字 3,但代碼本身繼續運行超過列表中的元素數量。 我使用了一個while循環,但這不起作用,通用if語句也沒有
listofnum = [7,6,21,12,3,99,8,3,0]
def recursion(x,counter):
if counter >= 0:
if x[0] == 3:
print("here")
recursion(x[1:],len(x)-1)
else:
print("next item...")
recursion(x[1:],len(x)-1)
else:
return "Done"
它確實找到了 3 次,但代碼處於無限循環中
我建議不要每次都傳遞一個新列表(通過切片列表),而是傳遞相同的列表並更新counter
值。
listofnum = [7,6,21,12,3,99,8,3,0]
def recursion(x, current_index=0):
if current_index >= len(x): # base condition
return
if x[current_index] == 3:
print("Got 3 at:", current_index)
recursion(x, current_index+1)
找到 3 時需要返回計數器,否則,切片列表並繼續。
listofnum = [7,6,21,12,3,99,8,3,0]
def recursion(x,counter):
if counter > 0:
if x[0] == 3:
return counter
else:
print("next item...")
return recursion(x[1:],len(x)-1)
else:
return -1
res = recursion(listofnum, len(listofnum))
print(res)
目前尚不清楚您如何調用遞歸函數,但我猜它的形式如下:
recursion(listofnum, len(listofnum))
在我的情況下,嘗試您的代碼,它正確地以
IndexError:列表索引超出范圍錯誤
由於“ counter >= 0
”條件,即使提供的列表根本沒有元素,這也會使您的代碼嘗試在位置0
上讀取,因此不存在 0(第一個)位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.