【发布时间】:2020-08-12 04:47:52
【问题描述】:
我正在尝试将一些数据结构实现为 Python 中的类(链表、二叉树、尝试等)。对于其中一些结构,我可以尝试将它们实现为dicts-of-dicts(例如,trie 为其子级嵌套层),或者我可以将它们实现为具有包含另一个实例的“下一个”变量对象。
我想知道递归数据结构与将所有子数据存储在成员变量中的优缺点是什么。有速度或内存优势吗?更好的缓存?可读性?
下面是一些示例代码,说明了我在说什么,但我更感兴趣的是理论上的好处,而不是对我的伪代码的批评:)
class Trie:
def __init__(self) -> None:
self._trie = {}
def insert(self, text: str) -> None:
trie = self._trie
for char in text:
if char not in trie:
trie[char] = {}
trie = trie[char]
trie["END"] = True
def search(self, prefix: str) -> bool:
trie = self._trie
for char in prefix:
if char not in trie:
return False
trie = trie[char]
return True
class RecursiveTrie:
def __init__(self) -> None:
self.children: List[Optional[RecursiveTrie]] = [None] * 26
self.end_of_word = False
def insert(self, key: str) -> None:
"""
If not present, inserts key into trie.
If the key is prefix of trie node, just marks leaf node.
"""
if not key:
self.end_of_word = True
return
index = self.char_to_index(key[0])
if self.children[index] is None:
self.children[index] = RecursiveTrie()
child = self.children[index]
child.insert(key[1:])
def search(self, key: str) -> bool:
""" Search key in the trie. Returns true if key is present in trie. """
if not key:
return True
index = self.char_to_index(key[0])
if self.children[index] is None:
return False
return self.children[index].search(key[1:])
【问题讨论】:
标签: python data-structures trie recursive-datastructures