88 lines
1.8 KiB
Python
88 lines
1.8 KiB
Python
# Bryan Schumaker (8 / 12 / 2010)
|
|
|
|
classes = set([str, int, unicode])
|
|
|
|
class DLTree:
|
|
def __init__(self, parent=None):
|
|
self.parent = parent
|
|
self.child_fwd = dict()
|
|
self.child_bck = dict()
|
|
|
|
def disp(self, level=0):
|
|
space = " " * level
|
|
children = self.children
|
|
|
|
if children == None:
|
|
return
|
|
|
|
keys = children.keys()
|
|
keys.sort()
|
|
|
|
for key in keys:
|
|
if key.__class__ in classes:#== str or key.__class__ == int or key.__class__ == unicode:
|
|
#value = children[key]
|
|
yield key
|
|
#value.disp(level+1)
|
|
|
|
#if len(self.children) == 0:
|
|
# print self.get_path()
|
|
|
|
def walk_path(self, path):
|
|
if len(path) == 0:
|
|
return True
|
|
p = path[0]
|
|
if p not in self.child_fwd:
|
|
return False
|
|
child = self.child_fwd[p]
|
|
val = child.walk_path(path[1:])
|
|
if val == True:
|
|
return child.child_fwd.keys()
|
|
return val
|
|
|
|
def walk_backwards(self, child=None):
|
|
cmp = self.child_bck.get(child, None)
|
|
if self.parent == None:
|
|
return [cmp]
|
|
child = self
|
|
path = self.parent.walk_backwards(child)
|
|
if cmp != None:
|
|
path.append(cmp)
|
|
return path
|
|
|
|
def walk_forwards(self):
|
|
children = self.child_fwd
|
|
|
|
keys = children.keys()
|
|
keys.sort()
|
|
|
|
for key in keys:
|
|
child = children[key]
|
|
has_children = False
|
|
for result in child.walk_forwards():
|
|
has_children = True
|
|
res = [key]
|
|
if result != None:
|
|
res += result
|
|
yield res
|
|
# A leaf will have no children, but
|
|
# still needs to yield a value
|
|
if has_children == False:
|
|
yield [key]
|
|
|
|
def insert(self, path):
|
|
cmp = path[0]
|
|
child = None
|
|
try:
|
|
child = self.child_fwd[cmp]
|
|
except TypeError:
|
|
child = DLTree(self)
|
|
self.child_fwd[cmp] = child
|
|
self.child_bck[child] = cmp
|
|
except KeyError:
|
|
child = DLTree(self)
|
|
self.child_fwd[cmp] = child
|
|
self.child_bck[child] = cmp
|
|
if len(path) > 1:
|
|
return child.insert(path[1:])
|
|
return self
|