1 from __future__ import print_function
6 def __init__(self, prefix):
14 self.root = prefixNode("")
16 def insert(self, prefix, node=None):
18 insert a prefix into the tree
23 parts = prefix.split(".")
27 for i in range(1, length + 1):
28 name = ".".join(parts[:i])
29 if not self.exists(name) and not name == prefix:
32 if prefix.startswith(node.prefix):
33 if prefix == node.prefix:
35 elif not node.children:
36 node.children.append(prefixNode(prefix))
39 for child in node.children:
40 if prefix.startswith(child.prefix):
41 self.insert(prefix, child)
44 node.children.append(prefixNode(prefix))
46 def load(self, prefix_list):
48 load a list of prefixes into the tree
50 for prefix in prefix_list:
53 def exists(self, prefix, node=None):
55 returns true if the specified prefix exists anywhere in the tree,
61 if not prefix.startswith(node.prefix):
63 elif node.prefix == prefix:
65 elif not node.children:
68 for child in node.children:
69 if prefix.startswith(child.prefix):
70 return self.exists(prefix, child)
72 def best_match(self, prefix, node=None):
74 searches the tree and returns the prefix that best matches the
80 if prefix.startswith(node.prefix):
83 for child in node.children:
84 if prefix.startswith(child.prefix):
85 return self.best_match(prefix, child)
88 def dump(self, node=None):
96 for child in node.children:
97 print(child.prefix, end=' ')
99 for child in node.children: