I'm trying to search for a word within my trie data structure and if it exists in the trie, return the word and its frequency.
This is what the trie looks like:
{'c': {'u': {'t': {('e', 10): True, ('s', 50): True},
('t', 30): True,
('b', 15): True},
'a': {'l': {('m', 1000): True}}},
'a': {'n': {('t', 20): True,
'n': {'o': {'t': {'a': {'t': {'i': {'o': {('n', 5): True}}}}}}}},
'p': {'p': {'l': {('e', 300): True},
'e': {'n': {'d': {'i': {('x', 10): True}}}},
('s', 60): True},
'o': {'l': {'o': {'g': {('y', 600): True,
'e': {'t': {'i': {('c', 1000): True}}}}}}}}},
'f': {'u': {'r': {'t': {'h': {'e': {('r', 40): True}}},
'n': {'i': {'t': {'u': {'r': {('e', 500): True}}}}}},
('r', 10): True},
'i': {'n': {('d', 400): True}},
'a': {'r': {('m', 5000): True,
'm': {'i': {'n': {('g', 1000): True}}, 'e': {('r', 300): True}}},
't': {'h': {'o': {('m', 40): True}}}}}}
Say I'm searching for the word cuts, how would I go about coding that so that I can return its integer pair which in this case is 50?
Btw the True part marks the end of the word.
This is my search function in psedocode format:
def search(self, word: str) -> int:
current = self.root
if word in current.children:
return its integer pair if its the end of a word and matches
return 0
Here's the Trie class:
# Class representing a node in the Trie
class TrieNode:
def __init__(self, letter=None, frequency=None, is_last=False):
self.letter = letter # letter stored at this node
self.frequency = frequency # frequency of the word if this letter is the end of a word
self.is_last = is_last # True if this letter is the end of a word
self.children: dict[str, TrieNode] = {} # a hashtable containing children nodes, key = letter, value = child node
class TrieDictionary(BaseDictionary):
def __init__(self):
# TO BE IMPLEMENTED
#setting root to object TrieNode()
self.root = TrieNode()
Basically for the output of my trie I printed out self.root.children