-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQ20_T9.py
84 lines (66 loc) · 1.81 KB
/
Q20_T9.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
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
import unittest
class TrieNode:
def __init__(self):
self.children = {}
self.terminating = False
class Trie:
def __init__(self):
self.root = TrieNode()
def add_word(self, word):
cur = self.root
for i in range(len(word)):
c = word[i]
if c not in cur.children:
cur.children[c] = TrieNode()
cur = cur.children[c]
cur.terminating = True
def search(self, word):
cur = self.root
for i in range(len(word)):
c = word[i]
if c not in cur.children:
return False
cur = cur.children[c]
return cur.terminating
def starts_with(self, prefix):
cur = self.root
for i in range(len(prefix)):
c = prefix[i]
if c not in cur.children:
return False
cur = cur.children[c]
return True
letters = {
1: "",
2: "abc",
3: "def",
4: "ghi",
5: "jkl",
6: "mno",
7: "pqrs",
8: "tuv",
9: "wxyz",
0: "",
}
def T9(code, words_trie):
words_output = []
def backtrack(idx=0, prefix=""):
if idx == len(str(code)):
if words_trie.search(prefix):
words_output.append(prefix)
return
if not words_trie.starts_with(prefix):
return
number = int(str(code)[idx])
for letter in letters[number]:
backtrack(idx + 1, prefix + letter)
backtrack()
return words_output
class Test(unittest.TestCase):
def test_t9(self):
words = ["tree", "used", "been", "deer", "moon"]
trie = Trie()
for word in words:
trie.add_word(word)
self.assertEqual(["tree", "used"], T9(8733, trie))
self.assertEqual(["moon"], T9(6666, trie))