Skip to content

Commit 3faa0cc

Browse files
committed
Add len() support to Trie
1 parent c9728b8 commit 3faa0cc

2 files changed

Lines changed: 10 additions & 3 deletions

File tree

pythainlp/util/trie.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,18 +16,19 @@ def __init__(self):
1616
self.children = {}
1717

1818
def __init__(self, words: Iterable[str]):
19-
self.words = words
19+
self.words = set(words)
2020
self.root = Trie.Node()
2121

2222
for word in words:
23-
self.add_word(word)
23+
self.add(word)
2424

25-
def add_word(self, word: str) -> None:
25+
def add(self, word: str) -> None:
2626
"""
2727
Add a word to the trie.
2828
2929
:param str text: a word
3030
"""
31+
self.words.add(word)
3132
cur = self.root
3233
for ch in word:
3334
child = cur.children.get(ch)
@@ -62,6 +63,9 @@ def __contains__(self, key: str) -> bool:
6263
def __iter__(self) -> Iterable[str]:
6364
yield from self.words
6465

66+
def __len__(self) -> int:
67+
return len(self.words)
68+
6569

6670
def dict_trie(dict_source: Union[str, Iterable[str], Trie]) -> Trie:
6771
"""

tests/test_util.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,9 @@ def test_trie(self):
250250
self.assertIsNotNone(Trie(Trie(["ทดสอบ", "ทดลอง"])))
251251

252252
trie = Trie(["ทด", "ทดสอบ", "ทดลอง"])
253+
self.assertTrue("ทด" in trie)
254+
trie.add("ทบ")
255+
self.assertEqual(len(trie), 4)
253256
self.assertEqual(len(trie.prefixes("ทดสอบ")), 2)
254257

255258
self.assertIsNotNone(dict_trie(Trie(["ลอง", "ลาก"])))

0 commit comments

Comments
 (0)