Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python trie

# A very simple trie to put together quickly for coding problems
WORD_KEY = '$'

def build_trie(words, trie = dict()):
  for word in words: # Add each word - letter by letter
    node = trie
    for letter in word: 
      node = node.setdefault(letter, {}) # node = node[letter].child
    node[WORD_KEY] = word # Mark "leaf" with word
  return trie

def exists(trie, word, index = 0):
  if index >= len(word): return trie.get(WORD_KEY, None) == word
  return trie.get(WORD_KEY, None) == word or (word[index] in trie and exists(trie[word[index]], word, index + 1))



# API
trie = build_trie(["hello", "hello again", "bye"])
assert exists(trie, "hello")
assert exists(trie, "hello again")
assert exists(trie, "bye")
assert not exists(trie, "")
assert not exists(trie, "hel")
trie = build_trie(["bye again", "will miss you"], trie)
assert exists(trie, "hello")
assert exists(trie, "hello again")
assert exists(trie, "bye")
assert exists(trie, "bye again")
assert not exists(trie, "")
assert not exists(trie, "hel")
assert not exists(trie, "hello ")
assert not exists(trie, "hello ag")
assert not exists(trie, "byebye")
Comment

tri python

>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
Comment

PREVIOUS NEXT
Code Example
Python :: jupyter lab 
Python :: read a file and split the words python 
Python :: call a Python range() using range(start, stop, step) 
Python :: timeit jupyter 
Python :: python paramiko 
Python :: python get name of function 
Python :: pandas reorder columns by name 
Python :: paginate on APIView drf 
Python :: string startswith python 
Python :: discord py get channel id by name 
Python :: python list iterate in 1 line 
Python :: dataframe choose random 
Python :: how to check if a letter is lowercase in python 
Python :: how to round a number down in python 
Python :: python list comprehension if else 
Python :: finding the index of an item in a pandas df 
Python :: Python Tkinter timer animation 
Python :: converting jupyter notebook files to python 
Python :: python3 send mail 
Python :: import django-on-heroku 
Python :: print output python to file 
Python :: python django shell command 
Python :: python not jump next line 
Python :: python warning 
Python :: python remove last element from list 
Python :: how to practise python 
Python :: Simple pagination wrapper for discord.py. 
Python :: count lines in file python 
Python :: pandas number of columns 
Python :: python check if string is in input 
ADD CONTENT
Topic
Content
Source link
Name
2+7 =