Reputation: 53
I'm doing an assignment and here is what the class looks like:
class GameStateNode:
'''
A tree of possible states for a two-player, sequential move, zero-sum,
perfect-information game.
value: GameState -- the game state at the root of this tree
children: list -- all possible game states that can be reached from this
game state via one legal move in the game. children is None until grow
is called.
'''
def __init__(self, game_state):
''' (GameStateNode, GameState) -> NoneType
Initialize a new game state tree consisting of a single root node
that contains game_state.
'''
self.value = game_state
self.children = []
I then wrote these two functions in because I need a recursive str:
def __str__(self):
''' (GameStateNode) -> str '''
return _str(self)
def _str(node):
''' (GameStateNode, str) -> str '''
return ((str(node.value) + '\n') +
((str(child) for child in node.children) if node.children else ''))
Can somebody tell me what the problem is with my _str function?
Upvotes: 5
Views: 10336
Reputation: 1832
The problem is the part where you iterate over the children and convert them to strings:
(str(child) for child in node.children)
That is actually a generator expression, which can't be simply converted to a string and concatenated with the left part str(node.value) + '\n'
.
Before doing the string concatenation, you should probably join the strings that get created by the generator into a single string by calling join
. Something like this will join the strings using a comma:
','.join(str(child) for child in node.children)
In the end, your code should probably be simplified to something like
def _str(node):
''' (GameStateNode, str) -> str '''
return (str(node.value) + '\n' +
(','.join(str(child) for child in node.children) if node.children else ''))
Of course, you can join the strings with some other character or string, like '\n', if you want to.
Upvotes: 9