python - 遍历决策树并捕获每个节点

标签 python functional-programming tree decision-tree

我正在尝试一次遍历决策树一个节点。

每个节点可以有2-3条路径

在有3条路径的节点上,其中一条路径总是终点,有时也有一条路径

我们无法倒退,但可以重新开始

我们可用的功能是

getCurrentNode()        #returns string of current node's path from start (ex. 'A-B-A-A-B')
getCurrentNodePaths()       #returns number of possible paths from this node
startOver()         #puts us back at node 0
takePath(int pathNumber)    #traverse the decision tree down a desired path

我编写了这个伪代码,它应该递归地遍历每个节点,但仅限于“最左边”的路径

# Start
def walk(pathNumber):
  takePath(pathNumber)
  next_nodes_paths = getCurrentNodePaths()
  if next_nodes_paths.length > 0:
    walk(0)


startOver()
walk(0)

我怎样才能让它跟踪它去过的地方,重新开始,并采取新的路径

最佳答案

这将创建决策树模型。您可以使用 select_path 方法导航到某个节点。路径是一个类似“03231002”的字符串。您可以使用 apply_function 方法遍历整个树并在每个点应用一个函数。有一个遍历整棵树的示例。

def select_path(path):
    startOver()
    for pathNumber in path:
        takePath(int(pathNumber))

class Node:
    def __init__(self,path):
        self.path = path
        self.select()
        self.num_children = getCurrentNodePaths().length
        self.children = [Node(path+str(i)) for i in range(self.num_children)]

    def select(self):
        select_path(self.path)

    def apply_function(self, func, recursive=False):
        self.select()
        func()
        if recursive:
            for child in self.children:
                apply_function(self, func, recursive=True)

root = Node('')

#walk whole tree and apply function function:
#def function:
#    pass
#root.apply_function(function, recursive=True)

关于python - 遍历决策树并捕获每个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58125603/

相关文章:

python - ListCtrl 中的 ColourPickerCtrl

perl - 在 Perl 中如何使用 map() 将操作应用于散列的每个元素?

java - 递归计算树中的特殊节点

python - 在同一调用中从 Spark Dataframes split 方法中选择数组元素?

python - plt.tight_layout 带有长标题的错误?

haskell - 单子(monad)和 ZipList 以外的应用仿函数?

javascript - 函数式 JavaScript : how to implement Function. prototype.not

algorithm - 对二叉索引树概念了解较少

python - 如何合并嵌套元组

python - 在递归中分配局部变量