-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathwordtree.py
74 lines (72 loc) · 2.52 KB
/
wordtree.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
class WordTree:
def __init__(self):
self.root = WordNode("")
def add_word(self, word):
self.root.add_word(word)
def has_word(self, word):
return self.root.has_word(word)
def get_intersect(self, words):
return self.root.get_intersect("", words)
class WordNode:
def __init__(self, content):
self.content = content
self.isfinal = False
self.nexts = {}
def add_word(self, word):
if word == "":
self.isfinal = True
else:
first = word[0]
rest = word[1:]
if first in list(self.nexts):
self.nexts[first].add_word(rest)
else:
self.nexts[first] = WordNode(first)
self.nexts[first].add_word(rest)
def has_word(self, word):
if word == "":
return self.isfinal
else:
first = word[0]
rest = word[1:]
if first in list(self.nexts):
return self.nexts[first].has_word(rest)
else:
return False
def get_intersect(self, word, words):
candidates = []
if (len(words)==0) and self.isfinal:
candidates += [""]
if word != "":
first = word[0]
rest = word[1:]
if first in list(self.nexts):
if (rest == "") and (len(words)>0):
cands = self.nexts[first].get_intersect(words[0], words[1:])
elif (rest == ""):
if self.nexts[first].isfinal:
cands = [""]
else:
cands = []
else:
cands = self.nexts[first].get_intersect(rest, words)
cands = [first+cand for cand in cands]
candidates += cands
if len(words) > 0:
word = words[0]
words = words[1:]
first = word[0]
rest = word[1:]
if first in list(self.nexts):
if (rest == "") and (len(words)>0):
cands = self.nexts[first].get_intersect(words[0], words[1:])
elif (rest == ""):
if self.nexts[first].isfinal:
cands = [""]
else:
cands = []
else:
cands = self.nexts[first].get_intersect(rest, words)
cands = [first.upper()+cand for cand in cands]
candidates += cands
return candidates