"""
def __init__(self):
self.root = {}
- self.end = "~#END#~"
+ self.end = "~END~"
self.length = 0
def insert(self, item: Sequence[Any]):
>>> t.insert('tessera')
>>> t.insert('tesack')
>>> t['tes']
- {'t': {'~#END#~': '~#END#~', 'i': {'c': {'l': {'e': {'~#END#~': '~#END#~'}}}}}, 's': {'e': {'r': {'a': {'~#END#~': '~#END#~'}}}}, 'a': {'c': {'k': {'~#END#~': '~#END#~'}}}}
+ {'t': {'~END~': '~END~', 'i': {'c': {'l': {'e': {'~END~': '~END~'}}}}}, 's': {'e': {'r': {'a': {'~END~': '~END~'}}}}, 'a': {'c': {'k': {'~END~': '~END~'}}}}
"""
ret = self.__traverse__(item)
>>> len(t)
3
>>> t.root
- {'t': {'e': {'s': {'t': {'~#END#~': '~#END#~'}, 's': {'~#END#~': '~#END#~', 'e': {'l': {'~#END#~': '~#END#~'}}}}}}}
+ {'t': {'e': {'s': {'t': {'~END~': '~END~'}, 's': {'~END~': '~END~', 'e': {'l': {'~END~': '~END~'}}}}}}}
>>> t.__delitem__('test')
>>> len(t)
2
>>> t.root
- {'t': {'e': {'s': {'s': {'~#END#~': '~#END#~', 'e': {'l': {'~#END#~': '~#END#~'}}}}}}}
+ {'t': {'e': {'s': {'s': {'~END~': '~END~', 'e': {'l': {'~END~': '~END~'}}}}}}}
>>> for x in t:
... print(x)
tess
>>> len(t)
1
>>> t.root
- {'t': {'e': {'s': {'s': {'~#END#~': '~#END#~'}}}}}
+ {'t': {'e': {'s': {'s': {'~END~': '~END~'}}}}}
>>> for x in t:
... print(x)
tess
return None
return [x for x in node if x != self.end]
+ def repr_recursive(self, node, delimiter):
+ """
+ A friendly string representation of the contents of the Trie.
+
+ >>> t = Trie()
+ >>> t.insert([10, 0, 0, 1])
+ >>> t.insert([10, 0, 0, 2])
+ >>> t.insert([10, 10, 10, 1])
+ >>> t.insert([10, 10, 10, 2])
+ >>> t.repr_recursive(t.root, '.')
+ '10.[0.0.[1, 2], 10.10.[1, 2]]'
+ >>> print(t)
+ 10[00[1, 2], 1010[1, 2]]
+
+ """
+ child_count = 0
+ my_rep = ''
+ for child in node:
+ if child != self.end:
+ child_count += 1
+ child_rep = self.repr_recursive(node[child], delimiter)
+ if len(child_rep) > 0:
+ my_rep += str(child) + delimiter + child_rep + ", "
+ else:
+ my_rep += str(child) + ", "
+ if len(my_rep) > 1:
+ my_rep = my_rep[:-2]
+ if child_count > 1:
+ my_rep = f'[{my_rep}]'
+ return my_rep
+
+ def __repr__(self):
+ """
+ A friendly string representation of the contents of the Trie. Under
+ the covers uses repr_recursive with no delimiter
+
+ >>> t = Trie()
+ >>> t.insert([10, 0, 0, 1])
+ >>> t.insert([10, 0, 0, 2])
+ >>> t.insert([10, 10, 10, 1])
+ >>> t.insert([10, 10, 10, 2])
+ >>> print(t)
+ 10[00[1, 2], 1010[1, 2]]
+
+ """
+ return self.repr_recursive(self.root, '')
+
if __name__ == '__main__':
import doctest