8/35
Part 2 of 7 · CountsLearn
Counts on the nodes
Each node can also count the words that pass through it.
# how many words pass through or end at this node
COUNT = "#"
def insert_counted(trie, word):
node = trie
# the top: every word starts with the empty string
node[COUNT] = node.get(COUNT, 0) + 1
for ch in word:
node = node.setdefault(ch, {})
node[COUNT] = node.get(COUNT, 0) + 1
node[END] = True
def count_prefix(trie, prefix):
node = find_node(trie, prefix)
return 0 if node is None else node.get(COUNT, 0)
counted = {}
for word in CATALOG:
insert_counted(counted, word)
print([count_prefix(counted, p) for p in ["", "t", "te", "ten", "tents", "l", "lan", "x"]])
What is count_prefix(counted, ""), the count on the top?
Pick one to see what it prints.
Pick an answer above to see the rest