I try to use a Trie data structure for some coding problem. For each node in a trie, you typically put a a list of reference of its children. So, I thought about using defaultdict to create a default empty trie node if some children does not exists in a lookup. However, I don't know how to use defaultdict to refer to the class that enclose it.
I tried two methods, which were both failed. The following is what I tried.
from dataclasses import dataclass
from collections import defaultdict
@dataclass
class TrieNode():
is_word = False
children = defaultdict("TrieNode")
The code above produce
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 4, in TrieNode
TypeError: first argument must be callable or None
@dataclass
class TrieNode():
is_word = False
children = defaultdict(TrieNode)
The above will produce
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 4, in TrieNode
NameError: name 'TrieNode' is not defined
My question is about how do you use defaultdict to implement this elegantly.
Thank you very much in advance.