使用python遍历二叉决策树?

发布于 2024-09-03 04:32:02 字数 167 浏览 3 评论 0原文

如何使用python语言遍历二叉决策树。 给定一棵树,我想知道我们如何从根遍历到所需的叶子 所需叶子的特征以字典形式给出,假设并且必须从根遍历到叶子,并使用特征列表中给出的详细信息回答每个节点的问题。 决策树节点的格式为 ((问题)(左树)(右树)) 在遍历时,它应该回答每个节点的问题,并选择向左或向右遍历,直到叶子?

how to traverse a binary decision tree using python language.
given a tree,i want know how can we travesre from root to required leaf
the feature of the required leaf are given in an dictionary form assume and have to traverse from root to leaf answering the questions at each node with the details given in feature list..
the decision tree node has format ((question)(left tree)(right tree))
while traversing it should answer question at each node and an choose left or right and traverse till leaf?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最近可好 2024-09-10 04:32:02
def walk(node):
    answer = ask(node.question)
    if answer == left:
        walk(node.left_tree)
    else:
        walk(node.right_tree)

def ask(question):
       # get answer somehow
       # depending on the answer choose which subtree to traverse
       return answer
def walk(node):
    answer = ask(node.question)
    if answer == left:
        walk(node.left_tree)
    else:
        walk(node.right_tree)

def ask(question):
       # get answer somehow
       # depending on the answer choose which subtree to traverse
       return answer
攀登最高峰 2024-09-10 04:32:02

@TheMachineCharmer 是对的:递归是这里的关键字

我会在 @TheMachineCharmer 给出的好函数中添加一点返回(简单的情况,答案既不是左也不是右),

def walk(node):
    answer = ask(node.question)
    if answer == left:
        walk(node.left_tree)
    else:
        walk(node.right_tree)
    return answer

这样如果节点包含真正的答案,它将返回它。

@TheMachineCharmer is right: recursivity is the keyword here!

I'd add to the nice function given by @TheMachineCharmer a little return (the trivial case, where answer is neither left nor right)

def walk(node):
    answer = ask(node.question)
    if answer == left:
        walk(node.left_tree)
    else:
        walk(node.right_tree)
    return answer

This way if the node contains THE real answer it will return it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文