If you ever need this it's here for you: an infinite default dictionary
from collections import defaultdict
inf = lambda: defaultdict(inf)
inf_dict = defaultdict(inf)
"""
>>> inf_dict[1][2][3][4]
defaultdict(<function <lambda> at 0x104dc0360>, {})
"""
Here's me using it in a dead simple implementation of a prefix trie.
class Trie:
def __init__(self):
inf = lambda: defaultdict(inf)
self.root = defaultdict(inf)
def insert(self, word: str) -> None:
root = self.root
for char in word:
point = ord(char) - ord('a')
root[point]["contains"] = True
root = root[point]
root["$"] = True
def search(self, word: str) -> bool:
root = self.root
for char in word:
point = ord(char) - ord('a')
root = root[point]
return root["$"]
def query(self, prefix: str) -> bool:
root = self.root
for char in prefix:
point = ord(char) - ord('a')
if not root[point]["contains"]:
return False
root = root[point]
return True