Repository navigation
Expand file tree
/
Copy pathtrie.py
More file actions
85 lines (74 loc) · 2.59 KB
/
Copy pathtrie.py
File metadata and controls
85 lines (74 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""A Unicode word set backed by a trie, including the empty word.
Add, membership, and discard take O(L) expected time. Completions are iterative,
sort child edges, and construct visited prefixes; their cost includes that text.
Returned words use Python's lexicographic order. No normalization is performed.
>>> words = Trie(['car', 'cat', 'cat', 'dog'])
>>> words.words('ca')
['car', 'cat']
>>> words.discard('car')
True
"""
from collections.abc import Iterable
class Trie:
def __init__(self, words: Iterable[str] = ()):
self._root = {}
self._size = 0
for word in words:
self.add(word)
def __len__(self) -> int:
return self._size
def _node(self, word: str):
if not isinstance(word, str):
raise TypeError("word must be a string")
node = self._root
for char in word:
if char not in node:
return None
node = node[char]
return node
def __contains__(self, word: str) -> bool:
node = self._node(word)
return node is not None and "" in node
def add(self, word: str) -> None:
if not isinstance(word, str):
raise TypeError("word must be a string")
node = self._root
for char in word:
node = node.setdefault(char, {})
if "" not in node:
node[""] = True
self._size += 1
def discard(self, word: str) -> bool:
if word not in self:
return False
node, parents = self._root, []
for char in word:
parents.append((node, char))
node = node[char]
del node[""]
self._size -= 1
for parent, char in reversed(parents):
if parent[char]:
break
del parent[char]
return True
def words(self, prefix: str = "", *, limit: int | None = None) -> list[str]:
if limit is not None and (
isinstance(limit, bool) or not isinstance(limit, int) or limit < 0
):
raise ValueError("limit must be a nonnegative integer or None")
node = self._node(prefix)
if node is None or limit == 0:
return []
stack, result = [(node, prefix)], []
while stack:
node, word = stack.pop()
if "" in node:
result.append(word)
if limit is not None and len(result) >= limit:
break
stack.extend(
(node[char], word + char)
for char in sorted((key for key in node if key), reverse=True)
)
return result