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

Class RadixNode

data_structures/trie/radix_tree.py:8–191  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

6
7
8class RadixNode:
9 def __init__(self, prefix: str = "", is_leaf: bool = False) -> None:
10 # Mapping from the first character of the prefix of the node
11 self.nodes: dict[str, RadixNode] = {}
12
13 # A node will be a leaf if the tree contains its word
14 self.is_leaf = is_leaf
15
16 self.prefix = prefix
17
18 def match(self, word: str) -> tuple[str, str, str]:
19 """Compute the common substring of the prefix of the node and a word
20
21 Args:
22 word (str): word to compare
23
24 Returns:
25 (str, str, str): common substring, remaining prefix, remaining word
26
27 >>> RadixNode("myprefix").match("mystring")
28 ('my', 'prefix', 'string')
29 """
30 x = 0
31 for q, w in zip(self.prefix, word):
32 if q != w:
33 break
34
35 x += 1
36
37 return self.prefix[:x], self.prefix[x:], word[x:]
38
39 def insert_many(self, words: list[str]) -> None:
40 """Insert many words in the tree
41
42 Args:
43 words (list[str]): list of words
44
45 >>> RadixNode("myprefix").insert_many(["mystring", "hello"])
46 """
47 for word in words:
48 self.insert(word)
49
50 def insert(self, word: str) -> None:
51 """Insert a word into the tree
52
53 Args:
54 word (str): word to insert
55
56 >>> RadixNode("myprefix").insert("mystring")
57
58 >>> root = RadixNode()
59 >>> root.insert_many(['myprefix', 'myprefixA', 'myprefixAA'])
60 >>> root.print_tree()
61 - myprefix (leaf)
62 -- A (leaf)
63 --- A (leaf)
64 """
65 # Case 1: If the word is the prefix of the node

Callers 3

insertMethod · 0.85
test_trieFunction · 0.85
mainFunction · 0.85

Calls

no outgoing calls

Tested by 1

test_trieFunction · 0.68