I'm having trouble implementing a recursive depth-first search on a tree structure in python 2.7, could anyone point me in the right direction?
Code
class node(object):
def __init__(self, value,children=[]):
self.value=value
self.children=children
def __repr__ (self,level=0):
ret = "\t"*level+repr(self.value)+"\n"
for child in self.children:
ret +=child.__repr__(level+1)
return ret
def search(self,st):
if self.value==st:
return True
else:
if not self.children:
return False
else:
for child in self.children:
self.search(st)
sample data structure (for simple pasting):
tree = node("fashion",[
node("garment",[
node("t-shirt"),
node("shorts")]),
node("designer",[
node("Ralf"),
node("tommy"),
node("joe")])
])
EDIT: the problem is that I'm ending in an infinate loop when searching, for example:
tree.search("garment")
EDIT 2: update to fix the recursion not advancing (thanks Ben!), but not getting a False answer to tree.search("joe")
def search(self,st):
if self.value==st:
return True
else:
if self.children:
for child in self.children:
return child.search(st)
else:
return False
EDIT 3: astute observations from Sharth have led me to
def search(self,st):
if self.value==st:
return True
for child in self.children:
if child.search(st):
return True
return False
Which works great, but searching
>>>tree.search("p")
produces
Traceback (most recent call last): File "", line 1, in tree.search("p") File "", line 15, in search if child.search(st): AttributeError: 'list' object has no attribute 'search'
why is that happening?
EDIT4: works when using the above data structure, but fails with a third level of data, i.e.
tree = node("fashion",[
node("garment",[
node("t-shirt"),
node("shorts")]),
node("designer",[
node("Ralf"),
node("tommy"),
node("joe"),[
node("fresh")]
])
])
edit 5: messed up the braces in edit four.