-
Notifications
You must be signed in to change notification settings - Fork 0
/
trie.py
executable file
·58 lines (35 loc) · 1.3 KB
/
trie.py
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
class Trie():
"""Trie data structure."""
def __init__(self):
self.isLeaf = False
self.children = {}
def insert(self, word):
"""Insert a word."""
current = self
for char in word:
current = current.children.setdefault(char, Trie())
current.isLeaf = True
def in_trie(self, word):
"""Check if a word is in the trie."""
current = self
for char in word:
current = current.children.get(char)
if not current:
return False
return current.isLeaf
def search(self, search_chars):
"""Get all words in the trie beginning with the given search characters"""
current = self
for char in search_chars:
current = current.children.get(char)
if not current:
return []
def search_matches(trie, phrase):
suggestions = []
if trie.isLeaf:
suggestions = [phrase]
# children is a dictionary: keys=characters, values=tries
for char, child in trie.children.items():
suggestions.extend(search_matches(child, f"{phrase}{char}"))
return suggestions
return search_matches(current, search_chars)