Skip to content

Commit d4c4616

Browse files
committed
[Feature] Added basic Trie data structure.
1 parent 9f3b23c commit d4c4616

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ $ coverage report -m
4343
* [SDBM Hash Function](structures/hash_map.py)
4444
* [Lose/Lose Hash Function](structures/hash_map.py)
4545
* [Heap](structures/heap.py)
46+
* [Trie](structures/trie.py)
4647

4748
### Algorithms
4849

structures/trie.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Trie():
2+
3+
eof = '__eof__'
4+
5+
def __init__(self, words):
6+
self.head = {}
7+
for word in words:
8+
current = self.head
9+
for letter in word:
10+
current = current.setdefault(letter, {})
11+
current[self.eof] = self.eof
12+
13+
def add(self, word):
14+
current = self.head
15+
for letter in word:
16+
current = current.setdefault(letter, {})
17+
current[self.eof] = self.eof

tests/test_trie.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import unittest
2+
from structures.trie import Trie
3+
4+
class TestTrie(unittest.TestCase):
5+
6+
def test_trie(self):
7+
trie = Trie(['hello','hel','headway','tree','second','true'])
8+
9+
self.assertTrue(Trie.eof in trie.head['h']['e']['l'])
10+
self.assertTrue(Trie.eof in trie.head['t']['r']['e']['e'])
11+
self.assertTrue(Trie.eof in trie.head['h']['e']['l']['l']['o'])
12+
13+
def test_add(self):
14+
trie = Trie(['1',])
15+
16+
with self.assertRaises(KeyError):
17+
trie.head['2']
18+
19+
trie.add('2')
20+
21+
self.assertTrue(Trie.eof in trie.head['2'])

0 commit comments

Comments
 (0)