Skip to content

Instantly share code, notes, and snippets.

@danielbarkhorn
Last active July 25, 2018 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielbarkhorn/4421b5036673f43c268b5f85a8f6cbec to your computer and use it in GitHub Desktop.
Save danielbarkhorn/4421b5036673f43c268b5f85a8f6cbec to your computer and use it in GitHub Desktop.
Simple Trie Python Implementation. Comment structure based off SKLearn.
class Trie:
"""
Trie data structure implemented using dictionary
Parameters
----------
dictioanry : array
An array of all the strings to be included in the trie
Attributes
----------
trie : dictionary
dictionary with nested dictionaries representing branches of trie. Presence of
key: '' with value '' represents termination node.
Examples
--------
Dictionary containing cat, car, and cone
Trie View:
c
/ \
a o
/ \ \
t r n
\
e
Dict View: {'c': {'a': {'t': {'': ''}, 'r': {'': ''}}}, 'o': {'n': {'e': {'': ''}}}}
"""
def __init__(self, dictionary):
self.trie = {}
for word in dictionary:
currentLevel = self.trie
for letter in word:
currentLevel = currentLevel.setdefault(letter, {})
currentLevel[''] = ''
def search(self, word, searchType='Exists'):
"""
Search trie for given word
Parameters
----------
word : string
word to be searched for in trie
searchType : 'Exists', 'Complete', 'Substring', default: 'Exists'
Type of search to run.
If 'Exists', will return true if search word exists as
full word or beginning of word in trie.
If 'Substring', will return true if search word exists strictly
as beginning of word in trie.
If 'Complete', will return true if search word exists as
full wod in trie.
Returns
-------
True / False
"""
currentLevel = self.trie
for letter in word:
if letter in currentLevel:
currentLevel = currentLevel[letter]
else:
return False
if searchType == 'Substring':
return '' not in currentLevel
if searchType == 'Complete:
return '' in currentLevel
return True
def getDictKeys(self, word):
"""
Search trie for given word
Parameters
----------
word : string
Returns
-------
nextLetters : array
Array of all the potential following letters given word.
Includes '' if complete word exists in dictionary
"""
currentLevel = self.trie
if not self.search(word, exists=True):
return {}
else:
for letter in word:
currentLevel = currentLevel[letter]
nextLetters = currentLevel.keys()
return nextLetters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment