python - Return dictionary from recursive function -
i have binary search tree each node represents game length. have return dictionary key length of game , value number of games of length. recursion call goes through every node in tree returns incorrect dictionary. i'm positive problem how i'm returning dictionary. appreciated
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) child in node.children] return game_len
in general, there 2 ways handle return values recursive algorithm. either can collect return values recursive calls , combine them, or can pass in mutable argument recursive calls can modify. think latter best in situation, since dictionaries easy mutate in place not easy merge together:
def game_lengths(node, result=none): if result none: result = {} #... add value result dict, handle base cases, etc. child in node.children: game_lengths(child, result) return result
Comments
Post a Comment