Val trees walk values
Val trees can walk through their values in addition to their paths. A doubly-linked val tree can also walk values backwards.
This commit is contained in:
parent
fe449ffea4
commit
2949535aba
|
@ -121,6 +121,18 @@ class ValTree(Tree):
|
|||
def __disp__(self, child, level):
|
||||
return "%s (%s)", (child, self[child].value)
|
||||
|
||||
def __walk_vals__(self, path):
|
||||
node = self
|
||||
res = []
|
||||
for key in path:
|
||||
node = node[key]
|
||||
res.append(node.value)
|
||||
return res
|
||||
|
||||
def walk_vals(self):
|
||||
for path in self.walk():
|
||||
yield self.__walk_vals__(path)
|
||||
|
||||
def insert(self, path, values):
|
||||
child = self.__insert__(path)
|
||||
if len(values) > 0:
|
||||
|
@ -137,6 +149,19 @@ class DLValTree(DLTree, ValTree):
|
|||
DLTree.__init__(self)
|
||||
ValTree.__init__(self)
|
||||
|
||||
def walk_vals_backwards(self, child = None):
|
||||
key = None
|
||||
if child != None:
|
||||
idc = id(child)
|
||||
key = [i[0] for i in self.items() if id(i[1]) == idc]
|
||||
if self.parent == None:
|
||||
return [self[key[0]].value]
|
||||
ret = self.parent.walk_vals_backwards(self)
|
||||
if key:
|
||||
return ret + [self[key[0]].value]
|
||||
else:
|
||||
return ret
|
||||
|
||||
def insert(self, path, values):
|
||||
child = self.__insert__(path)
|
||||
child.parent = self
|
||||
|
|
|
@ -45,6 +45,8 @@ from libsaria import trees
|
|||
#tree.insert(["a", "b", "c", "e"], [1, 2, 3, 5])
|
||||
#tree.insert(["f", "g", "h", "i"], [6, 7, 8, 9])
|
||||
#tree.disp()
|
||||
#for vals in tree.walk_vals():
|
||||
# print vals
|
||||
|
||||
|
||||
tree = trees.DLValTree()
|
||||
|
@ -52,7 +54,11 @@ n = tree.insert(["a", "b", "c", "d"], [1, 2, 3, 4])
|
|||
o = tree.insert(["a", "b", "c", "e"], [1, 2, 3, 5])
|
||||
p = tree.insert(["f", "g", "h", "i"], [6, 7, 8, 9])
|
||||
tree.disp()
|
||||
|
||||
for path in tree.walk_vals():
|
||||
print path
|
||||
print n.walk_backwards()
|
||||
print n.walk_vals_backwards()
|
||||
print o.walk_backwards()
|
||||
print o.walk_vals_backwards()
|
||||
print p.walk_backwards()
|
||||
print p.walk_vals_backwards()
|
||||
|
|
Loading…
Reference in New Issue