繁体   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