构建一个特定的str



这是主类:

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 = []

以下是我目前正在开发的功能:

def game_descriptions(root):
    ''' (GameStateNode) -> list of str
    Return a list containing a str describing each complete game that is
    possible from the game stored at root.
    Assume root is the root of a game state tree specifically for the game
    Subtract Square.
    >>> s = SubtractSquareState('p1', current_total = 6)
    >>> root = GameStateNode(s)
    >>> root.grow()
    >>> game_descriptions(root)
    ['p1:6 -> p2:2 -> p1:1 -> p2:0 = p1 wins!', 'p1:6 -> p2:5 -> p1:1 -> p2:0 = p1 wins!', 'p1:6 -> p2:5 -> p1:4 -> p2:0 = p1 wins!', 'p1:6 -> p2:5 -> p1:4 -> p2:3 -> p1:2 -> p2:1 -> p1:0 = p2 wins!']
    '''

def _build_paths(root, L = []):
    ''' (GameStateNode) -> list of str '''
    if root.children:
        for child in root.children:
            a = abbreviated(root.value)
            a += ' -> {}'.format(abbreviated(child.value))
            L.append(a)
            _build_paths(child, L)  
    else:
        pass
    return L
def abbreviated(s):
    '''(GameState) -> str
    Return an abbreviated str representation of SubtractSquareState s.
    '''
    return "{}:{}".format(s.next_player, s.current_total)

正如你在fcn game_descriptions中看到的那样,我需要返回一个游戏状态列表,按顺序排列,最后是获胜者。我当前的问题是fcn _build_path。我希望它返回一个没有获胜者的游戏描述列表,因为我将实现谁在fcn game_descriptions中获胜。我想要这个,例如:

>>> root = GameStateNode(SubtractSquareState('p1', current_total = 4))
>>> root.grow()
>>> _build_paths(root)
['p1:4 -> p2:0', 'p1:4 -> p2:3 -> p1:2 -> p2:1 -> p1:0']

相反,我得到了这个:

['p1:4 -> p2:0', 'p1:4 -> p2:3', 'p2:3 -> p1:2', 'p1:2 -> p2:1', 'p2:1 -> p1:0']

因为您想要一个字符串列表,所以需要从所有字符串列表中单独构建一个指示当前路径的字符串。您也可以使用它来指示起点,这样就可以避免在每个路径中列出每个节点两次。

如果没有你所有的代码,我就无法测试它,但我认为这种通用形式的东西会起作用:

def _build_paths(root, currentpath, L = []):
    ''' (GameStateNode) -> list of str '''
    if root.children:
        for child in root.children:
            a = ' -> {}'.format(abbreviated(child.value))
            currentpath += a
            _build_paths(child, currentpath, L)  
    else:
        L.append(currentpath)
    return L

你可以用来称呼它

_build_paths(root, abbreviated(root.value))

相关内容

最新更新