Python Trie实现为什么创建临时变量
Python Trie implementation why create temporary variable
我看了这段代码:
>>> _end = '_end_'
>>>
>>> def make_trie(*words):
... root = dict()
... for word in words:
... current_dict = root
... for letter in word:
... current_dict = current_dict.setdefault(letter, {})
... current_dict = current_dict.setdefault(_end, _end)
... return root
...
>>> make_trie('foo', 'bar', 'baz', 'barz')
{'b': {'a': {'r': {'_end_': '_end_', 'z': {'_end_': '_end_'}},
'z': {'_end_': '_end_'}}},
'f': {'o': {'o': {'_end_': '_end_'}}}}
来自这个link:How to create a TRIE in Python,但我不太明白为什么作者要创建临时变量current_dict,因为您总是只是在编辑名为root 的字典。 ..
I don't quite understand why does the author create the temporary variable current_dict since you are always just editing the dictionary called root...
不,你不是。如果它一直在编辑根字典,结果就会大不相同。每次执行循环内的赋值:
... current_dict = root
... for letter in word:
... current_dict = current_dict.setdefault(letter, {}) # this one
current_dict
被设置为更深一层的字典。此循环遍历特里,根据需要使用 setdefault
构建缺失的部分。我们必须将 setdefault
结果分配给 current_dict
以继续向下而不是停留在顶层,并且我们必须使用单独的 current_dict
变量而不是 root
所以我们可以指定 current_dict = root
在我们完成一个单词后返回顶层。
我看了这段代码:
>>> _end = '_end_'
>>>
>>> def make_trie(*words):
... root = dict()
... for word in words:
... current_dict = root
... for letter in word:
... current_dict = current_dict.setdefault(letter, {})
... current_dict = current_dict.setdefault(_end, _end)
... return root
...
>>> make_trie('foo', 'bar', 'baz', 'barz')
{'b': {'a': {'r': {'_end_': '_end_', 'z': {'_end_': '_end_'}},
'z': {'_end_': '_end_'}}},
'f': {'o': {'o': {'_end_': '_end_'}}}}
来自这个link:How to create a TRIE in Python,但我不太明白为什么作者要创建临时变量current_dict,因为您总是只是在编辑名为root 的字典。 ..
I don't quite understand why does the author create the temporary variable current_dict since you are always just editing the dictionary called root...
不,你不是。如果它一直在编辑根字典,结果就会大不相同。每次执行循环内的赋值:
... current_dict = root
... for letter in word:
... current_dict = current_dict.setdefault(letter, {}) # this one
current_dict
被设置为更深一层的字典。此循环遍历特里,根据需要使用 setdefault
构建缺失的部分。我们必须将 setdefault
结果分配给 current_dict
以继续向下而不是停留在顶层,并且我们必须使用单独的 current_dict
变量而不是 root
所以我们可以指定 current_dict = root
在我们完成一个单词后返回顶层。