2020-07-11 09:02:32 +08:00
|
|
|
import unittest
|
2017-03-30 17:38:16 +08:00
|
|
|
|
|
|
|
|
2020-07-11 09:02:32 +08:00
|
|
|
class TestTrie(unittest.TestCase):
|
2017-03-30 17:38:16 +08:00
|
|
|
|
|
|
|
def test_trie(self):
|
|
|
|
trie = Trie()
|
|
|
|
|
|
|
|
print('Test: Insert')
|
|
|
|
words = ['a', 'at', 'has', 'hat', 'he',
|
|
|
|
'me', 'men', 'mens', 'met']
|
|
|
|
for word in words:
|
|
|
|
trie.insert(word)
|
|
|
|
for word in trie.list_words():
|
2020-07-11 09:02:32 +08:00
|
|
|
self.assertTrue(trie.find(word) is not None)
|
2017-03-30 17:38:16 +08:00
|
|
|
|
|
|
|
print('Test: Remove me')
|
|
|
|
trie.remove('me')
|
|
|
|
words_removed = ['me']
|
|
|
|
words = ['a', 'at', 'has', 'hat', 'he',
|
|
|
|
'men', 'mens', 'met']
|
|
|
|
for word in words:
|
2020-07-11 09:02:32 +08:00
|
|
|
self.assertTrue(trie.find(word) is not None)
|
2017-03-30 17:38:16 +08:00
|
|
|
for word in words_removed:
|
2020-07-11 09:02:32 +08:00
|
|
|
self.assertTrue(trie.find(word) is None)
|
2017-03-30 17:38:16 +08:00
|
|
|
|
|
|
|
print('Test: Remove mens')
|
|
|
|
trie.remove('mens')
|
|
|
|
words_removed = ['me', 'mens']
|
|
|
|
words = ['a', 'at', 'has', 'hat', 'he',
|
|
|
|
'men', 'met']
|
|
|
|
for word in words:
|
2020-07-11 09:02:32 +08:00
|
|
|
self.assertTrue(trie.find(word) is not None)
|
2017-03-30 17:38:16 +08:00
|
|
|
for word in words_removed:
|
2020-07-11 09:02:32 +08:00
|
|
|
self.assertTrue(trie.find(word) is None)
|
2017-03-30 17:38:16 +08:00
|
|
|
|
|
|
|
print('Test: Remove a')
|
|
|
|
trie.remove('a')
|
|
|
|
words_removed = ['a', 'me', 'mens']
|
|
|
|
words = ['at', 'has', 'hat', 'he',
|
|
|
|
'men', 'met']
|
|
|
|
for word in words:
|
2020-07-11 09:02:32 +08:00
|
|
|
self.assertTrue(trie.find(word) is not None)
|
2017-03-30 17:38:16 +08:00
|
|
|
for word in words_removed:
|
2020-07-11 09:02:32 +08:00
|
|
|
self.assertTrue(trie.find(word) is None)
|
2017-03-30 17:38:16 +08:00
|
|
|
|
|
|
|
print('Test: Remove has')
|
|
|
|
trie.remove('has')
|
|
|
|
words_removed = ['a', 'has', 'me', 'mens']
|
|
|
|
words = ['at', 'hat', 'he',
|
|
|
|
'men', 'met']
|
|
|
|
for word in words:
|
2020-07-11 09:02:32 +08:00
|
|
|
self.assertTrue(trie.find(word) is not None)
|
2017-03-30 17:38:16 +08:00
|
|
|
for word in words_removed:
|
2020-07-11 09:02:32 +08:00
|
|
|
self.assertTrue(trie.find(word) is None)
|
2017-03-30 17:38:16 +08:00
|
|
|
|
|
|
|
print('Success: test_trie')
|
|
|
|
|
|
|
|
def test_trie_remove_invalid(self):
|
|
|
|
print('Test: Remove from empty trie')
|
|
|
|
trie = Trie()
|
2020-07-11 09:02:32 +08:00
|
|
|
self.assertTrue(trie.remove('foo') is None)
|
2017-03-30 17:38:16 +08:00
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
test = TestTrie()
|
|
|
|
test.test_trie()
|
2020-07-11 09:02:32 +08:00
|
|
|
test.assertRaises(KeyError, test.test_trie_remove_invalid)
|
2017-03-30 17:38:16 +08:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2020-07-11 09:02:32 +08:00
|
|
|
main()
|