-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
python SortedList 源码简析 #267
Comments
python SortedList 源码简析#267 SortedList 源码简析 (python)[toc] 原文地址:#267 随手写的一些笔记, 前言:S 代表着什么?新一代有序容器 SortedList与基于树的实现相比,使用列表具有一些基于内存使用情况的优势。
代码整体关系SortedList 根据传不传 key 分为 SortedList、SortedKeyList,不传 key 时降低了函数调用的开销。这里 出发点:短列表的快速插入删除传统的基于树的设计具有更好的理论复杂度,但这忽略了当今软件和硬件的现实。 实现细节 1:分块+线段树
实现细节 2:动态扩容与收缩策略
Q:线段树是怎么处理插入删除的?块分裂时需要在序列中插入一个新的块,合并时则需要删除块,这两个操作用线段树似乎不好处理。 源码中的技巧
_lists = self._lists
_maxes = self._maxes
_add = self.add
如果添加的元素太多 values = sorted(iterable)
if _maxes:
if len(values) * 4 >= self._len:
_lists.append(values)
values = reduce(iadd, _lists, [])
values.sort()
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
def append(self, value):
"""Raise not-implemented error.
Implemented to override `MutableSequence.append` which provides an
erroneous default implementation.
:raises NotImplementedError: use ``sl.add(value)`` instead
"""
raise NotImplementedError("use ``sl.add(value)`` instead")
class SortedItemsView(ItemsView, Sequence):
"""Sorted items view is a dynamic view of the sorted dict's items.
When the sorted dict's items change, the view reflects those changes.
The items view implements the set and sequence abstract base classes.
"""
__slots__ = ()
@classmethod
def _from_iterable(cls, it):
return SortedSet(it)
def __getitem__(self, index):
_mapping = self._mapping
_mapping_list = _mapping._list
if isinstance(index, slice):
keys = _mapping_list[index]
return [(key, _mapping[key]) for key in keys]
key = _mapping_list[index]
return key, _mapping[key]
__delitem__ = _view_delitem 结尾看到这里,不由感叹 SortedList 的作者 Grant Jenks 大叔功力之深厚,创作出了这么优秀的模板。 参考https://www.zhihu.com/question/593450942/answer/2966795898 F&Q
|
|
可以改进的地方
|
No description provided.
The text was updated successfully, but these errors were encountered: