[英]Python recursion depth exceeded limit exceeded, and don't know how to delete recursion
[英]How to limit the depth of recursion in python?
我有一個元素列表。 我想知道列表中是否有兩對元素,其中一對元素具有相同的值。
我的想法是,我首先比較列表中的所有元素,如果找到一對,則從列表中刪除該對,然后再次進行。 因此,我認為我可以使用遞歸來完成此任務,但是將深度限制為2即可解決問題。
這是我的第一次嘗試:
recursion_depth=0
def is_twopair(card):
nonlocal recursion_depth
if recursion_depth==2: return True
for i in range(0, len(card)):
for k in range(i+1,len(card)):
if card[i].value==card[k].value:
del card[k], card[i]
recursion_depth+=1
is_twopair(card)
else: continue
else: continue
else: return False
我使用變量recursion_depth記錄了遞歸的深度,但隨后意識到return命令不會立即終止函數並返回true,而是返回其原始調用者is_twopair(card)。 所以我的問題是:
我知道也許有幾種方法可以解決此問題。 但是我想忠實於自己的想法,並將其作為學習的機會。
我不相信您可以在沒有一些嚴重的黑魔法的情況下“脫離”遞歸,也不相信您應該嘗試這樣做。 在返回鏈上級聯返回值通常是一種很好的方法。
我個人將避免使用非局部變量,並在每個函數調用的范圍內跟蹤遞歸深度。
def remove_pairs(card, count=2, depth=0):
if depth == count:
return card
for i in range(0, len(card)):
for j in range(i+1, len(card)):
if card[i].value == card[j].value:
del card[j], card[i]
return remove_pairs(card, count, depth+1) # add return here
將深度跟蹤移到函數本身中將允許從不同位置重復調用該函數而不會出現問題。
此外,可以使用itertools.combinations
清理一些代碼。
from itertools import combinations
def remove_pairs(cards, count=2, depth=0):
if depth == count:
return cards
for card1, card2 in combinations(cards, 2):
if card1.value == card2.value:
cards.remove(card1)
cards.remove(card2)
return remove_pairs(cards, count, depth+1)
yourList = [1,1,2,2,3,4]
yourDict = {}
for i in yourList:
yourDict[i] = yourList.count(i)
此代碼將返回列表中每個值的出現次數,因此您可以確定對數。
在這種情況下:
yourDict--> {1:2,2:2,3:3:1,4:1}
值1出現2次,值2出現2次,值3和4出現1次。
我認為您所缺少的是return
調用,以將遞歸調用的結果傳遞給前一個調用者:
if card[i].value==card[k].value:
del card[k], card[i]
recursion_depth+=1
return is_twopair(card) # add return here!
我真的不認為遞歸是解決此問題的自然方法,但是通過上述更改,它應該可以工作。 您可以通過將depth
作為可選參數傳遞來避免使用nonlocal
變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.