使用anytree模块在Python中创建动态树

时间:2019-11-03 09:47:29

标签: python anytree

我尝试为minmax算法创建实现,并且需要创建具有所有可能动作的树。使用python 3.7中的anytree模块创建树,但是当尝试在第一个树级别进行迭代并构建下一个级别时会收到错误。

Traceback (most recent call last):
Hello from the pygame community. https://www.pygame.org/contribute.html
  File "C:/Users/User/PycharmProjects/Tema5AI/Main.py", line 217, in <module>
min_max_algorithm(game)
  File "C:/Users/User/PycharmProjects/Tema5AI/Main.py", line 209, in min_max_algorithm
new_node = Node((game, i, 0), parent=(pre, fill, node))
  File "C:\Users\User\PycharmProjects\Tema5AI\venv\lib\site-packages\anytree\node\node.py", line 66, in __init__
    self.parent = parent
  File "C:\Users\User\PycharmProjects\Tema5AI\venv\lib\site-packages\anytree\node\nodemixin.py", line 126, in parent
    msg = "Parent node %r is not of type 'NodeMixin'." % (value)
TypeError: not all arguments converted during string formatting

我的构建树代码是:

def min_max_algorithm(game):
    first_black_move = util.get_all_available_black(game)
    root = Node(game)
    for i in first_black_move:
        node = Node((game, i, 0), parent=root)
    for pre, fill, node in RenderTree(root):
        first_white_move = util.get_all_available_white(game)
        for i in first_white_move:
            new_node = Node((game, i, 0), parent=(pre, fill, node))
    for pre, fill, node in RenderTree(root):
        print("%s%s" % (pre, node.name))

更确切的问题是:     如何遍历当前树将子级添加到节点?

以下问题对我没有帮助: How to specify childrens in anytree and print a tree

Read data from a file and create a tree using anytree in python

How can I implement a tree in Python? Are there any built in data structures in Python like in Java?

1 个答案:

答案 0 :(得分:0)

该异常具有误导性。我创建了票证https://github.com/c0fec0de/anytree/issues/121

您可以随时添加节点。请确保仅将节点对象设置为父对象或子对象。也许最好使用迭代器代替呈现函数,即PreOrderIter。请尝试这个

def min_max_algorithm(game):
    first_black_move = util.get_all_available_black(game)
    root = Node(game)
    for i in first_black_move:
        node = Node((game, i, 0), parent=root)
    for n in PreOrderIter(root):
        first_white_move = util.get_all_available_white(game)
        for i in first_white_move:
            new_node = Node((game, i, 0), parent=n)
    for pre, fill, node in RenderTree(root):
        print("%s%s" % (pre, node.name))