在基于二叉树的Python程序中保存所有节点

2024-06-06 08:03:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试添加一种存储和检索程序animal.py获得的知识的方法,这是一个“20个问题”的学习算法,通过一个二叉决策树来工作。(请点击链接查看原始程序)

在最初的程序中,我为每个节点添加了“向上”状态,以指向决策树中某个节点的父节点,以便更容易在树中上下移动。我还使用regex将所有非字母数字用户输入更改为空格,因此用户不会混淆我的两个新函数:

def know(know):
    #Load preset knowledge
    p=node("")
    knowledge=p
    for char in know:
            if char not in "+-":p.question+=char
            if char=="+":
                    p.right=node("")
                    p.right.up=p
                    p.left=node("")
                    p.left.up=p
                    p=p.right
            if char=="-": p=p.up.left
    return knowledge

def output(node,accum=""):
    #Output all knowledge
    accum=accum+node.question
    if node.right!= None : accum=output(node.right,accum+"+")
    if node.left!= None : accum=output(node.left,accum+"-")
    return accum

函数“output”被设计成返回作为单个字符串传递给它的节点下的完整树,用“+”和“-”字符表示该字符串要跟随哪个节点。函数“know”应该取前面由“output”创建的字符串,创建二叉决策树并返回指向顶部节点的指针。这是一个不太起作用的部分,我无法理解。(目前,我正在将初始知识字符串直接输入到程序源代码中:加载和保存文件将稍后添加,这似乎是一项微不足道的任务)

例如:output(know('mineral+crystal+quartz obsidian nothing'))返回:“mineral+crystal+quartz obsidiannothing-”

它应该返回原始字符串:“矿物+水晶+石英-黑曜石”

我确信这在理论上应该行得通,但我遇到了困难,我真的不明白为什么不行。在

我的想法是错的,还是我试图实现它?有没有更好的方法来存储从原始程序创建的决策树?在

我是一个狂热的读者,但第一次张贴到stackoverflow,并对这个网站上的人才感到敬畏,所以我非常期待你的想法。在


Tags: 函数字符串程序rightnode决策树outputif
2条回答

根据请求,我无法找到“猜猜动物”的实现,但我确实找到了由它生成的存档pickle文件。值得注意的是,我不需要原始的应用程序来解释它:

>>> import pickle
>>> with open('animal.pickle') as inf:
...     animals = pickle.load(inf)
... 
>>> import pprint
>>> pprint.pprint(animals)
['is it fuzzy',
 ['does it have a tail',
  ['is it a pack hunter',
   'dog',
   ['does it have thumbs',
    'lemur',
    ['Does it have a bushy tail',
     'chipmunk',
     ['Does it have a horn', 'rhinoceros', 'cat']]]],
  'chimp'],
 ['can it breathe air',
  ['Does it have feathers',
   'cockatoo',
   ['Does it have 8 legs', 'spider', 'iguana']],
  'catfish']]

将树创建为嵌套列表的程序的实现留给读者作为练习。据我回忆,它的篇幅和一般方法与问题中链接的内容大致相同,它将使你熟悉列表操作。在

pickle module可以序列化和取消序列化复杂结构。这应该很简单:

with open('animal.dat', 'w') as outf:
    pickle.dump(knowledge, outf)

以及

^{pr2}$

正如他们所说,"the batteries are included"所以学习标准库使困难的事情变得容易,even flying。在

相关问题 更多 >