From: Scott Gasch Date: Fri, 24 Sep 2021 17:03:18 +0000 (-0700) Subject: Trie repr. X-Git-Url: https://wannabe.guru.org/gitweb/?a=commitdiff_plain;h=0338feb616bee4ba7bcd3b51748c4b79569cca0f;p=python_utils.git Trie repr. --- diff --git a/trie.py b/trie.py index be7a48d..b9a5a1a 100644 --- a/trie.py +++ b/trie.py @@ -13,7 +13,7 @@ class Trie(object): """ def __init__(self): self.root = {} - self.end = "~#END#~" + self.end = "~END~" self.length = 0 def insert(self, item: Sequence[Any]): @@ -90,7 +90,7 @@ class Trie(object): >>> 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) @@ -125,12 +125,12 @@ class Trie(object): >>> 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 @@ -139,7 +139,7 @@ class Trie(object): >>> len(t) 1 >>> t.root - {'t': {'e': {'s': {'s': {'~#END#~': '~#END#~'}}}}} + {'t': {'e': {'s': {'s': {'~END~': '~END~'}}}}} >>> for x in t: ... print(x) tess @@ -240,6 +240,53 @@ class Trie(object): 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