簡體   English   中英

從遞歸函數返回字典

[英]Return dictionary from recursive function

我有一個二叉搜索樹,其中每個節點代表一個游戲長度。 我必須返回一個字典,其中鍵是游戲的長度,值是具有該長度的游戲數量。 遞歸調用遍歷樹中的每個節點,但它返回一個不正確的字典。 我很確定問題是我如何歸還字典。 任何幫助將不勝感激

game_len = {}
if not node.children:
    key = len(node.possible_next_moves())
    if key not in game_len:
        game_len[key] = 1
    else:
        game_len[key] += 1
else:
    key = len(node.possible_next_moves())
    if key not in game_len:
        game_len[key] = 1
    else:
        game_len[key] += 1
    [game_lengths(child) for child in node.children] 
return game_len

通常,有兩種方法可以處理遞歸算法的返回值。 您可以從遞歸調用中收集返回值並將它們組合起來,或者您可以傳入一個額外的可變參數,遞歸調用可以修改該參數。 我認為后者在這種情況下可能是最好的,因為字典很容易就地變異,但不太容易合並在一起:

def game_lengths(node, result=None):
    if result is None:
        result = {}

    #... add a value to the result dict, handle base cases, etc.

    for child in node.children:
        game_lengths(child, result)

    return result

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM