【发布时间】:2021-04-22 06:14:31
【问题描述】:
我尝试使用 Trie 数据结构来解决一些编码问题。 对于 trie 中的每个节点,您通常会放置一个其子节点的引用列表。 因此,如果查找中不存在某些子节点,我考虑使用 defaultdict 创建一个默认的空 trie 节点。 但是,我不知道如何使用 defaultdict 来引用包含它的类。
我尝试了两种方法,都失败了。以下是我尝试过的。
from dataclasses import dataclass
from collections import defaultdict
@dataclass
class TrieNode():
is_word = False
children = defaultdict("TrieNode")
上面的代码产生
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)
以上会产生
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 4, in TrieNode
NameError: name 'TrieNode' is not defined
我的问题是如何使用defaultdict 优雅地实现这一点。
非常感谢您。
【问题讨论】:
-
为什么不使用列表?
-
或者从
trie上的维基百科条目中的代码开始?
标签: python trie defaultdict