-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremoveColor.py
More file actions
90 lines (73 loc) · 2.24 KB
/
removeColor.py
File metadata and controls
90 lines (73 loc) · 2.24 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
86
87
88
89
"""
The code removes colors from a sentence using trie data structure
which stores prefixes of colours.
Input: List of colors and sentence
Output: Sentence after removing colours
"""
from utilities import COLOR_SET
import re
"""
Create a trie to store list of strings with a word as a key.
"""
class Node(object):
def __init__(self, end_node=False):
self.end_node = end_node
self.children = {}
class Trie(object):
def __init__(self):
self.root = Node()
def insert(self, key):
"""
Split a string and store the prefix as the child of
the root.
"""
current = self.root
for k in key.split():
# print k
if k not in current.children:
current.children[k] = Node()
current = current.children[k]
current.end_node = True
def search(self, key):
"""
Search a word as a child of the root and return
pointer to the node.
"""
current = self.root
if key not in current.children:
return False
else:
return current.children[key]
db = Trie()
for colors in COLOR_SET:
db.insert(colors.lower())
def removeColor(sentence):
"""
Creates a trie from list of colors.
Uses this trie to remove color names from sentence
"""
# stringIndexed = sentence.split()
stringIndexed = re.findall(r"[\w']+", sentence)
index = 0
while index <= len(stringIndexed) - 1:
# print stringIndexed[index],index,stringIndexed[index+1]
j = index
# print index
current = db.search(stringIndexed[index])
if current:
while (current and current.children and stringIndexed[j + 1] in current.children):
current = current.children[stringIndexed[j + 1]]
j = j + 1
if current.end_node:
del stringIndexed[index:j + 1]
# print stringIndexed
# print index
index = index - 1
else:
index = j + 1
# print "index is",index
else:
index = index + 1
return ' '.join(stringIndexed)
# if __name__ == '__main__':
# print removeColor("jabra solemate nfc wireless bluetooth speakers (black)".lower())