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 :: find key by value python 
Python :: add key value in each dictonary in the list 
Python :: python __new__ 
Python :: python call function by string 
Python :: how to save python variables locally 
Python :: reading an image using opencv library 
Python :: python default dictionary 
Python :: python else syntax 
Python :: python beautifulsoup get attibute 
Python :: check if object is list python 
Python :: python add 1 
Python :: activate venv in python 
Python :: How to assign value to variable in Python 
Python :: print numbers from 1 to 100 in python 
Python :: grab the first letter of each string in an array python 
Python :: python3 password generator script 
Python :: how to add items in list in python at specific position 
Python :: Python NumPy asfarray Function Example List to float type array 
Python :: nested python list 
Python :: addition array numpy 
Python :: python infinite loop 
Python :: flask set mime type 
Python :: printing in python 
Python :: Mixed Fractions in python 
Python :: pip install not happening in python cmd 
Python :: gnuplot sum over a column 
Python :: file = Root() path = file.fileDialog() print("PATH = ", path) 
Python :: how to use list compression with conditional formatting 
Shell :: lumen run command 
Shell :: uninstall k3s 
ADD CONTENT
Topic
Content
Source link
Name
2+8 =