我一直想弄清楚如何遞歸地調用python中的函數在過去的幾天無濟於事。我構建了一個樹結構來存儲對象,並且不僅使用生成器遍歷樹,而且還對遞歸調用我的find函數時遇到問題。構建樹數據結構時遞歸調用的問題
這是我的代碼。
class Node:
def __init__(self, data, children=list()):
self.data = data
self.children = children
def __eq__(self, node):
return self.data == node.data
def __str__(self):
return self.data
def __repr__(self):
return self.data
def write_xtl(self, node, out_file, level=0):
gen2 = self.traverse(node)
for child in gen2:
out_file.write(child.data)
def traverse(self, node, path=list()):
yield self
for n in self.children:
for m in traverse(n, path):
yield m
def find(self, node):
if self == node:
return self
else:
for child in self.children:
return child.find(node)
def add(self, node, value):
entry_point = self.find(node)
if entry_point:
#print ("Found %s in %s") % (value.data.rstrip(), node.data.rstrip())
#print ("\tentry_point is %s") % (entry_point.data)
entry_point.children.append(value)
else:
print ("Could not find %s") % (value)
這是我的測試文件:
from xtensiltree import tree
root = tree.Node("root\n")
header = tree.Node("header\n")
orderHeader = tree.Node("orderHeader\n")
date = tree.Node("date\n")
notes = tree.Node("notes\n")
address = tree.Node("address\n")
contacts = tree.Node("contacts\n")
root.add(root, header)
root.add(header, orderHeader)
root.add(orderHeader, date)
root.add(orderHeader, notes)
root.add(orderHeader, address)
root.add(address, contacts)
outfile = open("ooutput.xtl", "w")
root.write_xtl(root, outfile)
outfile.close()
預先感謝您。
不幸的是,這不適用於我的代碼。我嘗試過我的find方法的各種迭代,並且我嘗試提高遞歸限制。不知道爲什麼始終達到最大遞歸深度。 – qream