我正在尝试一次遍历决策树一个节点。
每个节点可以有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/