2

I have a binary search tree where each node represents a game length. I have to return a dictionary where the key is the length of the game and the value is the number of games that are of that length. The recursion call goes through every node in the tree but it returns an incorrect dictionary. I'm positive that the problem is how I'm returning the dictionary. Any help will be 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) for child in node.children] 
return game_len
asked Mar 31, 2015 at 20:27
1
  • Could you add to the question how your code does not work? Commented Mar 31, 2015 at 20:30

1 Answer 1

6

In general, there are two ways to handle the return values from a recursive algorithm. Either you can collect the return values from your recursive calls and combine them, or you can pass in an extra mutable argument which the recursive calls can modify. I think the latter is likely to be best in this situation, since dictionaries are easy to mutate in place but not especially easy to merge together:

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
answered Mar 31, 2015 at 20:35
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.