简体   繁体   English

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

[英]Saving all nodes in binary tree based Python program

I have been trying to add a way of storing and retrieving knowledge gained by the program animal.py , which is a "20 questions" learning algorithm that works via a binary decision tree. 我一直在尝试添加一种存储和检索由animal.py程序获得的知识的方法,该程序是一种“ 20个问题”的学习算法,通过二进制决策树起作用。 (Please click link to see the original program) (请点击链接查看原始程序)

To the original program, I have added the state "up" to each node, to point to the parent of a node in the decision tree, in order to make it easier to move both up and down the tree. 在原始程序中,我将状态“ up”添加到每个节点,以指向决策树中节点的父节点,以使其更容易在树中上下移动。 I have also used regex to change all non-alphanumeric user input to spaces, so the user cannot confuse my two new functions: 我还使用了正则表达式将所有非字母数字用户输入更改为空格,因此用户不能混淆我的两个新功能:

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

The function "output" is designed to return the complete tree underneath the node passed to it as a single string, with "+" and "-" characters indicating which node the string is following down. 函数“输出”旨在返回作为单个字符串传递给它的节点下面的完整树,其中“ +”和“-”字符指示字符串在哪个节点之后。 The function "know" is supposed to take a string previously created by "output", create the binary decision tree and return a pointer to the top node. 函数“知道”应该采用先前由“输出”创建的字符串,创建二进制决策树,并返回指向顶部节点的指针。 This is the part that is not quite working that I cannot figure out. 这是我无法弄清楚的工作不充分的部分。 (Currently, I am inputing the initial knowledge string directly into the program source: loading and saving files will be added later, and seems a trivial task) (当前,我正在将初始知识字符串直接输入到程序源中:加载和保存文件将在以后添加,这似乎是一项琐碎的任务)

Eg: output(know('mineral+crystal+quartz-obsidian-nothing')) returns: 'mineral+crystal+quartz-obsidiannothing-' 例如:output(know('mineral + crystal + quartz-obsidian-nothing'))返回:'mineral + crystal +石英-obsidiannothing-'

where it should return the original string: 'mineral+crystal+quartz-obsidian-nothing' 它应返回原始字符串的位置:“ mineral + crystal + quartz-obsidian-nothing”

I am sure this should work (in theory), but I have hit a wall and am really lost as to why it is not. 我确信这在理论上是可行的,但是我碰壁了,对于为什么不这样做,我真的迷失了。

Is my idea wrong, or just my attempt to implement it? 我的想法错了吗,还是我只是试图实现它? Is there a better way to store the created decision tree from the original program? 有没有更好的方法来存储原始程序中创建的决策树?

I am an avid reader but first time poster to stackoverflow, and am in awe of the talent on this site, so I very much look forward your ideas. 我是一个狂热的读者,但是第一次成为stackoverflow的发布者,并且对此站点的人才感到敬畏,因此,我非常期待您的想法。

The pickle module can serialize and unserialize complicated structures. pickle模块可以序列化和反序列化复杂的结构。 This should be as simple as: 这应该很简单:

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

and

with open('animal.dat', 'r') as inf:
    knowledge = pickle.load(inf)

As they say, "the batteries are included" so learning the standard library makes hard things easy, even flying . 正如他们所说的, “包括电池”,因此学习标准库可以使艰苦的事情变得轻松, 甚至飞起来

Per request, I was unable to find my implementation of "guess the animal" but I did find an archived pickle file generated by it. 根据请求,我无法找到“猜动物”的实现,但确实找到了由该生成的腌制文件。 It is worth noting that I didn't need the original app to be able to interpret it: 值得注意的是,我不需要原始应用程序就能解释它:

>>> 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']]

The implementation of the program that creates this tree-as-nested-lists is left as an exercise for the reader. 创建该嵌套目录树的程序的实现留给读者练习。 To my recollection, it was about the same length and general approach as the one linked in the question and it will get you familiar with list manipulation. 据我回忆,它的长度和通用方法与问题中链接的方法相同,并且使您熟悉列表操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM