Skip to content

Commit 93e01b0

Browse files
authored
Implement is_inserted method to check if string was inserted in Trie. (#517)
1 parent aafe3c2 commit 93e01b0

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

pydatastructs/strings/tests/test_trie.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,23 @@
22

33
def test_Trie():
44

5-
strings = ["A", "to", "tea", "ted", "ten", "i", "in", "inn"]
5+
strings = ["A", "to", "tea", "ted", "ten", "i",
6+
"in", "inn", "Amfn", "snbr"]
67
trie = Trie()
78
for string in strings:
89
trie.insert(string)
910

11+
prefix_strings = ["te", "t", "Am", "snb"]
12+
1013
for string in strings:
14+
assert trie.is_inserted(string)
15+
16+
for string in strings[::-1]:
17+
assert trie.is_inserted(string)
18+
19+
for string in prefix_strings:
1120
assert trie.is_present(string)
21+
assert not trie.is_inserted(string)
1222

1323
assert sorted(trie.strings_with_prefix("t")) == ['tea', 'ted', 'ten', 'to']
1424
assert sorted(trie.strings_with_prefix("te")) == ["tea", "ted", "ten"]
@@ -23,7 +33,17 @@ def test_Trie():
2333
trie.delete(string)
2434
for present in strings:
2535
if present == string:
26-
assert not trie.is_present(present)
36+
assert not trie.is_inserted(present)
2737
else:
2838
assert trie.is_present(present)
39+
assert trie.is_inserted(present)
2940
strings.remove(string)
41+
42+
prefix_strings_1 = ["dict", "dicts", "dicts_lists_tuples"]
43+
trie_1 = Trie()
44+
45+
for i in range(len(prefix_strings_1)):
46+
trie_1.insert(prefix_strings_1[i])
47+
for j in range(i + 1):
48+
assert trie_1.is_inserted(prefix_strings_1[j])
49+
assert trie_1.is_present(prefix_strings_1[j])

pydatastructs/strings/trie.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,28 @@ def is_present(self, string: str) -> bool:
104104
walk = walk.get_child(char)
105105
return True
106106

107+
def is_inserted(self, string: str) -> bool:
108+
"""
109+
Checks if the given string was inserted in the trie.
110+
111+
Parameters
112+
==========
113+
114+
string: str
115+
116+
Returns
117+
=======
118+
119+
True if the given string was inserted in trie;
120+
False in all other cases.
121+
"""
122+
walk = self.root
123+
for char in string:
124+
if walk.get_child(char) is None:
125+
return False
126+
walk = walk.get_child(char)
127+
return walk.is_terminal
128+
107129
def delete(self, string: str) -> bool:
108130
"""
109131
Deletes the given string from the trie.

0 commit comments

Comments
 (0)