MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / delete

Method delete

data_structures/trie/radix_tree.py:131–179  ·  view source on GitHub ↗

Deletes a word from the tree if it exists Args: word (str): word to be deleted Returns: bool: True if the word was found and deleted. False if word is not found >>> RadixNode("myprefix").delete("mystring") False

(self, word: str)

Source from the content-addressed store, hash-verified

129 return incoming_node.find(remaining_word)
130
131 def delete(self, word: str) -> bool:
132 """Deletes a word from the tree if it exists
133
134 Args:
135 word (str): word to be deleted
136
137 Returns:
138 bool: True if the word was found and deleted. False if word is not found
139
140 >>> RadixNode("myprefix").delete("mystring")
141 False
142 """
143 incoming_node = self.nodes.get(word[0], None)
144 if not incoming_node:
145 return False
146 else:
147 _matching_string, remaining_prefix, remaining_word = incoming_node.match(
148 word
149 )
150 # If there is remaining prefix, the word can't be on the tree
151 if remaining_prefix != "":
152 return False
153 # We have word remaining so we check the next node
154 elif remaining_word != "":
155 return incoming_node.delete(remaining_word)
156 # If it is not a leaf, we don't have to delete
157 elif not incoming_node.is_leaf:
158 return False
159 else:
160 # We delete the nodes if no edges go from it
161 if len(incoming_node.nodes) == 0:
162 del self.nodes[word[0]]
163 # We merge the current node with its only child
164 if len(self.nodes) == 1 and not self.is_leaf:
165 merging_node = next(iter(self.nodes.values()))
166 self.is_leaf = merging_node.is_leaf
167 self.prefix += merging_node.prefix
168 self.nodes = merging_node.nodes
169 # If there is more than 1 edge, we just mark it as non-leaf
170 elif len(incoming_node.nodes) > 1:
171 incoming_node.is_leaf = False
172 # If there is 1 edge, we merge it with its child
173 else:
174 merging_node = next(iter(incoming_node.nodes.values()))
175 incoming_node.is_leaf = merging_node.is_leaf
176 incoming_node.prefix += merging_node.prefix
177 incoming_node.nodes = merging_node.nodes
178
179 return True
180
181 def print_tree(self, height: int = 0) -> None:
182 """Print the tree

Callers 1

test_trieFunction · 0.95

Calls 2

matchMethod · 0.80
getMethod · 0.45

Tested by 1

test_trieFunction · 0.76