[英]Benefits to Recursive Data Structures in Python?
我正在嘗試將一些數據結構實現為 Python 中的類(鏈表、二叉樹、嘗試等)。 對於其中一些結構,我可以嘗試將它們實現為dicts-of-dicts(例如,trie 為其子級嵌套了層),或者我可以將它們實現為具有包含另一個相同實例的“下一個”變量object。
我想知道遞歸數據結構與將所有子數據存儲在成員變量中的優缺點是什么。 有速度或 memory 的好處嗎? 更好的緩存? 可讀性?
下面是一些示例代碼,說明了我在說什么,但我對理論上的好處比對我的偽代碼的批評更感興趣:)
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:])
IMO 這兩種方法中的哪一種真正取決於您要編寫的代碼是真實的生產代碼還是練習。
對於生產代碼,您應該為第一個版本 go,它更小且更易於閱讀。 它將dict
視為基本磚塊(就像在 Python 中一樣),嵌套 dicts 根本沒有問題(考慮到即使 python 中的每個 object 屬性都在dict
中......使用指向另一個實例而不使用 dict 的成員也不會乍一看似乎不是一個好主意)。
為了理解嘗試,第二個版本不依賴於字典(明確地),它是您在 C 甚至 C++ 中編寫它的方式,其中數組可能有意義,與std::map
和真正的生產硬件,今天的 CPU 太復雜了,無法預測復雜算法的性能)。 如果您將來需要用低級語言實現 trie 或 trie 的變體,那么這些知識將很有用。
生產 python 軟件中的第二個版本只會讓未來的同事和/或您自己的生活更加艱難。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.