Skip to content

Commit b5e6289

Browse files
committed
Add product repository
1 parent e9f36fb commit b5e6289

1 file changed

Lines changed: 78 additions & 0 deletions

File tree

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
class Node:
2+
def __init__(self):
3+
self.child = dict()
4+
self.word_count = 0
5+
6+
7+
def add_word(root, s):
8+
tmp = root
9+
for ch in s:
10+
if ch not in tmp.child:
11+
tmp.child[ch] = Node()
12+
13+
tmp = tmp.child[ch]
14+
tmp.word_count += 1
15+
16+
17+
def find_word(root, s):
18+
tmp = root
19+
for ch in s:
20+
if ch not in tmp.child:
21+
return []
22+
tmp = tmp.child[ch]
23+
return tmp
24+
25+
26+
def extract_words(found_node):
27+
result = []
28+
29+
if found_node.child:
30+
if found_node.word_count > 0:
31+
result.append('')
32+
if len(result) >= 3:
33+
return result
34+
35+
current_keys = sorted(list(found_node.child.keys()))
36+
for k in current_keys:
37+
for s in extract_words(found_node.child[k]):
38+
result.append(k + s)
39+
if len(result) >= 3:
40+
return result
41+
else:
42+
result.append('')
43+
return result
44+
45+
46+
def threeProductSuggestions(numProducts, repository, customerQuery):
47+
# WRITE YOUR CODE HERE
48+
root = Node()
49+
for i in range(numProducts):
50+
add_word(root, repository[i])
51+
52+
results = []
53+
for i in range(2, len(customerQuery) + 1):
54+
current_query = customerQuery[:i]
55+
found_node = find_word(root, current_query)
56+
if not found_node:
57+
break
58+
59+
result = extract_words(found_node)
60+
for k in range(len(result)):
61+
result[k] = current_query + result[k]
62+
63+
results.append(result)
64+
65+
return results
66+
67+
68+
# numProducts = 5
69+
# repository = ['mobile', 'mouse', 'moneypot', 'monitor', 'mouspad']
70+
# customerQuery = 'mouse'
71+
72+
73+
numProducts = 5
74+
repository = ['code', 'codePhone', 'coddle', 'coddles', 'codes']
75+
customerQuery = 'coddle'
76+
77+
78+
print(threeProductSuggestions(numProducts, repository, customerQuery))

0 commit comments

Comments
 (0)