machine learning - Saving all nodes in binary tree based Python program -


i have been trying add way of storing , retrieving knowledge gained program animal.py, "20 questions" learning algorithm works via binary decision tree. (please click link see original program)

to original program, have added state "up" each node, point parent of node in decision tree, in order make easier move both , down tree. have used regex change non-alphanumeric user input spaces, user cannot confuse 2 new functions:

def know(know):     #load preset knowledge     p=node("")     knowledge=p     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 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" designed return complete tree underneath node passed single string, "+" , "-" characters indicating node string following down. function "know" supposed take string created "output", create binary decision tree , return pointer top node. part not quite working cannot figure out. (currently, inputing initial knowledge string directly program source: loading , saving files added later, , seems trivial task)

eg: output(know('mineral+crystal+quartz-obsidian-nothing')) returns: 'mineral+crystal+quartz-obsidiannothing-'

where should return original string: 'mineral+crystal+quartz-obsidian-nothing'

i sure should work (in theory), have hit wall , lost why not.

is idea wrong, or attempt implement it? there better way store created decision tree original program?

i avid reader first time poster stackoverflow, , in awe of talent on site, forward ideas.

the pickle module can serialize , unserialize complicated structures. should simple as:

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

and

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

as say, "the batteries included" learning standard library makes hard things easy, even flying.


Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -