ocarina/libsaria/trees.py

69 lines
1.3 KiB
Python

# Bryan Schumaker (11/06/2010)
from libsaria.path import sep
class Tree(dict):
def __init__(self):
dict.__init__(self)
def __len__(self):
count = 0;
for path in self.walk():
count += 1
return count
def __disp__(self, child, level):
return "%s", child
def disp(self, level = 0):
for child in self:
space = " " * level
fmt, vals = self.__disp__(child, level)
print space, fmt % vals
self[child].disp(level + 1)
def walk(self):
keys = self.keys()
keys.sort()
for key in keys:
child = self[key]
if len(child.keys()) == 0:
yield [key]
continue
for res in child.walk():
yield [key] + res
def __insert__(self, path):
path_part = path[0]
child = self.get(path_part, None)
if child == None:
child = self.__class__()
self[path_part] = child
return child
def insert(self, path):
child = self.__insert__(path)
if len(path) > 1:
child.insert(path[1:])
class FSTree(Tree):
def __init__(self):
Tree.__init__(self)
def walk_paths(self):
for path in self.walk():
yield sep.join(path)
def insert_path(self, base, file = None):
path = base.split(sep)
self.insert_path_split(path, file)
def insert_path_split(self, base, file = None):
if file == None:
self.insert(base)
else:
self.insert(base + [file])