【问题标题】:Return dictionary from recursive function从递归函数返回字典
【发布时间】:2015-06-05 08:10:51
【问题描述】:

我有一个二叉搜索树,其中每个节点代表一个游戏长度。我必须返回一个字典,其中键是游戏的长度,值是具有该长度的游戏数。递归调用遍历树中的每个节点,但它返回一个不正确的字典。我很肯定问题在于我如何返回字典。任何帮助将不胜感激

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

【问题讨论】:

  • 您能否补充一下您的代码如何不起作用的问题?

标签: python dictionary recursion binary-tree


【解决方案1】:

一般来说,有两种方法可以处理递归算法的返回值。您可以从递归调用中收集返回值并将它们组合起来,或者您可以传入一个额外的可变参数,递归调用可以修改该参数。我认为后者在这种情况下可能是最好的,因为字典很容易就地变异,但不是特别容易合并在一起:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2021-06-11
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    相关资源
    最近更新 更多