| 1 |
Sorted Containers Introduction |
| 2 |
============================== |
| 3 |
|
| 4 |
.. currentmodule:: sortedcontainers |
| 5 |
|
| 6 |
.. contents:: |
| 7 |
:local: |
| 8 |
|
| 9 |
|
| 10 |
Installation |
| 11 |
------------ |
| 12 |
|
| 13 |
The first step to using any software library is getting it properly installed. |
| 14 |
There are several ways to install :doc:`Sorted Containers<index>`. |
| 15 |
|
| 16 |
The recommended way to install :doc:`Sorted Containers<index>` is using the |
| 17 |
`pip`_ command:: |
| 18 |
|
| 19 |
$ python3 -m pip install sortedcontainers |
| 20 |
|
| 21 |
You may also choose instead to use the newer `pipenv`_ command:: |
| 22 |
|
| 23 |
$ pipenv install sortedcontainers |
| 24 |
|
| 25 |
These commands will install the latest version of :doc:`Sorted |
| 26 |
Containers<index>` from the `Python Package Index`_. |
| 27 |
|
| 28 |
:doc:`Sorted Containers<index>` is actively developed on GitHub, where the code |
| 29 |
is `open source`_. You may choose to install directly from the source |
| 30 |
repository. First, you will need a copy of the sources. The recommended way to |
| 31 |
get a copy of the source repository is to clone the repository from GitHub:: |
| 32 |
|
| 33 |
$ git clone git://github.com/grantjenks/python-sortedcontainers.git |
| 34 |
|
| 35 |
You may also choose instead to download the `Sorted Containers tarball`_ or |
| 36 |
download the `Sorted Containers zipball`_. |
| 37 |
|
| 38 |
Once you have a copy of the sources, you can embed it in your Python package, |
| 39 |
or install it into your site-packages using the command:: |
| 40 |
|
| 41 |
$ python3 setup.py install |
| 42 |
|
| 43 |
:doc:`Sorted Containers<index>` is available in Debian distributions as |
| 44 |
`python3-sortedcontainers` and `python-sortedcontainers`. |
| 45 |
|
| 46 |
:doc:`Sorted Containers<index>` is looking for a CentOS/RPM package |
| 47 |
maintainer. If you can help, please open an issue in the `Sorted Containers |
| 48 |
Issue Tracker`_. |
| 49 |
|
| 50 |
.. _`pip`: https://pypi.org/project/pip/ |
| 51 |
.. _`pipenv`: https://pypi.org/project/pipenv/ |
| 52 |
.. _`Python Package Index`: https://pypi.org/project/sortedcontainers/ |
| 53 |
.. _`open source`: https://github.com/grantjenks/python-sortedcontainers |
| 54 |
.. _`Sorted Containers tarball`: https://github.com/grantjenks/python-sortedcontainers/tarball/master |
| 55 |
.. _`Sorted Containers zipball`: https://github.com/grantjenks/python-sortedcontainers/zipball/master |
| 56 |
.. _`Sorted Containers Issue Tracker`: https://github.com/grantjenks/python-sortedcontainers/issues |
| 57 |
|
| 58 |
|
| 59 |
Sorted List |
| 60 |
----------- |
| 61 |
|
| 62 |
At the core of :doc:`Sorted Containers<index>` is the mutable sequence data |
| 63 |
type :class:`SortedList`. The :class:`SortedList` maintains its values in |
| 64 |
ascending sort order. As with Python's built-in list data type, |
| 65 |
:class:`SortedList` supports duplicate elements and fast random-access |
| 66 |
indexing. |
| 67 |
|
| 68 |
>>> from sortedcontainers import SortedList |
| 69 |
>>> sl = SortedList() |
| 70 |
|
| 71 |
Values may be added to a :class:`SortedList` using either |
| 72 |
:func:`SortedList.update` or :func:`SortedList.add`. When doing so, the list |
| 73 |
remains sorted. |
| 74 |
|
| 75 |
>>> sl.update([5, 1, 3, 4, 2]) |
| 76 |
>>> sl |
| 77 |
SortedList([1, 2, 3, 4, 5]) |
| 78 |
>>> sl.add(0) |
| 79 |
>>> sl |
| 80 |
SortedList([0, 1, 2, 3, 4, 5]) |
| 81 |
|
| 82 |
Several methods may be used to remove elements by value or by index. The |
| 83 |
methods :func:`SortedList.discard` and :func:`SortedList.remove` remove |
| 84 |
elements by value. And the methods :func:`SortedList.pop` and |
| 85 |
:func:`SortedList.__delitem__` remove elements by index. All values may be |
| 86 |
removed using :func:`SortedList.clear`. |
| 87 |
|
| 88 |
>>> sl.remove(0) |
| 89 |
>>> sl.discard(1) |
| 90 |
>>> sl |
| 91 |
SortedList([2, 3, 4, 5]) |
| 92 |
>>> sl.pop() |
| 93 |
5 |
| 94 |
>>> del sl[1] |
| 95 |
>>> sl |
| 96 |
SortedList([2, 4]) |
| 97 |
>>> sl.clear() |
| 98 |
|
| 99 |
Because :class:`SortedList` is sorted, it supports efficient lookups by value |
| 100 |
or by index. When accessing values by index, the :class:`SortedList` can be |
| 101 |
used as an `order statistic tree`_. Rather than performing a linear scan, |
| 102 |
values can be found in logarithmic time by repeatedly bisecting the internal |
| 103 |
tree structure. Methods for looking up values are |
| 104 |
:func:`SortedList.__contains__`, :func:`SortedList.count`, |
| 105 |
:func:`SortedList.index`, :func:`SortedList.bisect_left`, |
| 106 |
:func:`SortedList.bisect_right`, and :func:`SortedList.__getitem__`. |
| 107 |
|
| 108 |
>>> sl = SortedList('abbcccddddeeeee') |
| 109 |
>>> 'f' in sl |
| 110 |
False |
| 111 |
>>> sl.count('e') |
| 112 |
5 |
| 113 |
>>> sl.index('c') |
| 114 |
3 |
| 115 |
>>> sl[3] |
| 116 |
'c' |
| 117 |
>>> sl.bisect_left('d') |
| 118 |
6 |
| 119 |
>>> sl.bisect_right('d') |
| 120 |
10 |
| 121 |
>>> sl[6:10] |
| 122 |
['d', 'd', 'd', 'd'] |
| 123 |
|
| 124 |
Several methods can be used to iterate values in a :class:`SortedList`. There |
| 125 |
are the typical sequence iterators: :func:`SortedList.__iter__` and |
| 126 |
:func:`SortedList.__reversed__`. There are also methods for iterating by value |
| 127 |
or by index using :func:`SortedList.irange` and |
| 128 |
:func:`SortedList.islice`. These methods produce iterators that are faster than |
| 129 |
repeatedly indexing the :class:`SortedList`. |
| 130 |
|
| 131 |
>>> sl = SortedList('acegi') |
| 132 |
>>> list(iter(sl)) |
| 133 |
['a', 'c', 'e', 'g', 'i'] |
| 134 |
>>> list(reversed(sl)) |
| 135 |
['i', 'g', 'e', 'c', 'a'] |
| 136 |
>>> list(sl.irange('b', 'h')) |
| 137 |
['c', 'e', 'g'] |
| 138 |
>>> list(sl.islice(1, 4)) |
| 139 |
['c', 'e', 'g'] |
| 140 |
|
| 141 |
A :class:`SortedList` also supports the typical sequence operators |
| 142 |
:func:`SortedList.__add__` and :func:`SortedList.__mul__` as well as their |
| 143 |
in-place counterparts. |
| 144 |
|
| 145 |
>>> sl = SortedList('abc') |
| 146 |
>>> sl + sl |
| 147 |
SortedList(['a', 'a', 'b', 'b', 'c', 'c']) |
| 148 |
>>> sl * 3 |
| 149 |
SortedList(['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']) |
| 150 |
>>> sl += 'de' |
| 151 |
>>> sl |
| 152 |
SortedList(['a', 'b', 'c', 'd', 'e']) |
| 153 |
>>> sl *= 2 |
| 154 |
>>> sl |
| 155 |
SortedList(['a', 'a', 'b', 'b', 'c', 'c', 'd', 'd', 'e', 'e']) |
| 156 |
|
| 157 |
Although :class:`SortedList` implements most of the mutable sequence methods, |
| 158 |
there are five which are not implemented. Each of these methods assigns a value |
| 159 |
at an index which is not supported by :class:`SortedList`. |
| 160 |
|
| 161 |
>>> sl = SortedList('abcde') |
| 162 |
>>> sl[2] = 'c' |
| 163 |
Traceback (most recent call last): |
| 164 |
... |
| 165 |
NotImplementedError: use ``del sl[index]`` and ``sl.add(value)`` instead |
| 166 |
>>> sl.reverse() |
| 167 |
Traceback (most recent call last): |
| 168 |
... |
| 169 |
NotImplementedError: use ``reversed(sl)`` instead |
| 170 |
>>> sl.append('f') |
| 171 |
Traceback (most recent call last): |
| 172 |
... |
| 173 |
NotImplementedError: use ``sl.add(value)`` instead |
| 174 |
>>> sl.extend(['f', 'g', 'h']) |
| 175 |
Traceback (most recent call last): |
| 176 |
... |
| 177 |
NotImplementedError: use ``sl.update(values)`` instead |
| 178 |
>>> sl.insert(5, 'f') |
| 179 |
Traceback (most recent call last): |
| 180 |
... |
| 181 |
NotImplementedError: use ``sl.add(value)`` instead |
| 182 |
|
| 183 |
Comparison with :class:`SortedList` uses lexicographical ordering as with other |
| 184 |
sequence types. |
| 185 |
|
| 186 |
Refer to the :doc:`Sorted List documentation<sortedlist>` for additional |
| 187 |
parameters, more examples, and descriptions of runtime complexity. |
| 188 |
|
| 189 |
.. _`order statistic tree`: https://en.wikipedia.org/wiki/Order_statistic_tree |
| 190 |
|
| 191 |
|
| 192 |
Sorted-key List |
| 193 |
--------------- |
| 194 |
|
| 195 |
The :doc:`Sorted Containers<index>` project also maintains a specialized |
| 196 |
sorted-list-like type that accepts a key-parameter as found in Python's |
| 197 |
built-in `sorted` function. :class:`SortedKeyList` provides the same |
| 198 |
functionality as :class:`SortedList` but maintains the order of contained |
| 199 |
values based on the applied key-function. This simplifies the pattern of boxing |
| 200 |
and un-boxing which would otherwise be required. |
| 201 |
|
| 202 |
>>> from operator import neg |
| 203 |
>>> from sortedcontainers import SortedKeyList |
| 204 |
>>> skl = SortedKeyList(key=neg) |
| 205 |
|
| 206 |
The key function extracts a comparison key for ordering items in the list. In |
| 207 |
our example above we apply the negation operator. In the example above, a |
| 208 |
sorted list of integers would be ordered in descending sort order. |
| 209 |
|
| 210 |
You can also construct a :class:`SortedKeyList` using the :class:`SortedList` |
| 211 |
type by passing a key-function to the initializer. |
| 212 |
|
| 213 |
>>> from sortedcontainers import SortedList |
| 214 |
>>> values = SortedList([1, 2, 3, 4, 5], key=neg) |
| 215 |
>>> values |
| 216 |
SortedKeyList([5, 4, 3, 2, 1], key=<built-in function neg>) |
| 217 |
>>> isinstance(values, SortedList) |
| 218 |
True |
| 219 |
>>> issubclass(SortedKeyList, SortedList) |
| 220 |
True |
| 221 |
>>> values.key |
| 222 |
<built-in function neg> |
| 223 |
|
| 224 |
:class:`SortedKeyList` adds three additional methods to the :class:`SortedList` |
| 225 |
type. They are :func:`SortedKeyList.bisect_key_left`, |
| 226 |
:func:`SortedKeyList.bisect_key_right`, and :func:`SortedKeyList.irange_key`. |
| 227 |
Each of these methods accepts the key rather than the value for its |
| 228 |
:class:`SortedList` counterpart. |
| 229 |
|
| 230 |
>>> skl = SortedKeyList([1, 2, 3, 4, 5], key=neg) |
| 231 |
>>> skl |
| 232 |
SortedKeyList([5, 4, 3, 2, 1], key=<built-in function neg>) |
| 233 |
>>> skl.bisect_key_left(-4.5) |
| 234 |
1 |
| 235 |
>>> skl.bisect_key_right(-1.5) |
| 236 |
4 |
| 237 |
>>> list(skl.irange_key(-4.5, -1.5)) |
| 238 |
[4, 3, 2] |
| 239 |
|
| 240 |
Refer to the :doc:`Sorted List documentation<sortedlist>` for additional |
| 241 |
parameters, more examples, and descriptions of runtime complexity. |
| 242 |
|
| 243 |
|
| 244 |
Caveats |
| 245 |
------- |
| 246 |
|
| 247 |
:doc:`Sorted Containers<index>` data types have three requirements: |
| 248 |
|
| 249 |
1. The comparison value or key must have a `total ordering`_. |
| 250 |
|
| 251 |
2. The comparison value or key must not change while the value is stored in the |
| 252 |
sorted container. |
| 253 |
|
| 254 |
3. If the key-function parameter is used, then equal values must have equal |
| 255 |
keys. |
| 256 |
|
| 257 |
If any of these three requirements are violated then the warranty of |
| 258 |
:doc:`Sorted Containers<index>` is void and it will not behave correctly. While |
| 259 |
it may be possible to design useful data types that do not have these |
| 260 |
requirements, these are the caveats of :doc:`Sorted Containers<index>` and they |
| 261 |
match those of :doc:`alternative implementations<performance>`. Each of these |
| 262 |
requirements allow for optimizations and together they are an attempt to find |
| 263 |
the right tradeoff between functionality and performance. |
| 264 |
|
| 265 |
Let's look at some examples of what works and what doesn't. In Python, all |
| 266 |
objects inherit from ``object`` which provides a default implementation of |
| 267 |
equality. In pseudocode, the object type looks something like: |
| 268 |
|
| 269 |
>>> class Object: |
| 270 |
... def __eq__(self, other): |
| 271 |
... return id(self) == id(other) |
| 272 |
|
| 273 |
The default implementation defines equality in terms of identity. Note that |
| 274 |
`Object` does not define comparison methods like less-than or |
| 275 |
greater-than. While Python objects are comparable by default in Python 2, the |
| 276 |
feature was removed in Python 3. Instances of `object` can *not* be stored in a |
| 277 |
:class:`SortedList`. |
| 278 |
|
| 279 |
We can extend this example by creating our own `Record` data type with `name` |
| 280 |
and `rank` attributes. |
| 281 |
|
| 282 |
>>> class Record(object): |
| 283 |
... def __init__(self, name, rank): |
| 284 |
... self.name = name |
| 285 |
... self.rank = rank |
| 286 |
... def __eq__(self, other): |
| 287 |
... return self.name == other.name |
| 288 |
|
| 289 |
The `Record` type defines equality in terms of its `name` attribute which may |
| 290 |
be thought of as a record identifier. Each `Record` also has a `rank` which |
| 291 |
would be useful for ranking records in sorted order. The `Record` type does not |
| 292 |
define comparison operators and so can *not* be stored in a |
| 293 |
:class:`SortedList`. |
| 294 |
|
| 295 |
>>> alice1 = Record('alice', 1) |
| 296 |
>>> bob2 = Record('bob', 2) |
| 297 |
>>> carol3 = Record('carol', 3) |
| 298 |
|
| 299 |
Since the `rank` attribute is intended for ordering records, the key-function |
| 300 |
presents a tempting but invalid use for ordering records:: |
| 301 |
|
| 302 |
>>> get_rank = lambda record: record.rank |
| 303 |
>>> sl = SortedList([alice1, bob2, carol3], key=get_rank) |
| 304 |
|
| 305 |
Although the sorted list now appears to work, the requirements have been |
| 306 |
invalidated. Specifically #3, since it is now possible for equal values to have |
| 307 |
inequal keys:: |
| 308 |
|
| 309 |
>>> bob4 = Record('bob', 4) |
| 310 |
>>> bob2 == bob4 # Equal values. |
| 311 |
True |
| 312 |
>>> get_rank(bob2) == get_rank(bob4) |
| 313 |
False |
| 314 |
>>> # ^-- Equal values should have equal keys. |
| 315 |
>>> bob4 in sl # <-- Here's the problem. BAD! |
| 316 |
False |
| 317 |
|
| 318 |
In the example above, `bob4` can not be found in `sl` because although `bob2` |
| 319 |
and `bob4` are equal, the corresponding keys are not equal. The mistake is a |
| 320 |
bit easier to see without the key-function. The key-function defined |
| 321 |
comparisons between records like so:: |
| 322 |
|
| 323 |
>>> class Record(object): |
| 324 |
... def __init__(self, name, rank): |
| 325 |
... self.name = name |
| 326 |
... self.rank = rank |
| 327 |
... def __eq__(self, other): |
| 328 |
... return self.name == other.name |
| 329 |
... def __lt__(self, other): |
| 330 |
... return self.rank < other.rank |
| 331 |
|
| 332 |
Written as above, equality between objects is more clearly seen as unrelated to |
| 333 |
ordering between objects. This is the most common mistake made when using |
| 334 |
:doc:`Sorted Containers<index>`. The `Record` type now also violates |
| 335 |
requirement #1 because equal instances can also be strictly less than each |
| 336 |
other:: |
| 337 |
|
| 338 |
>>> bob2 = Record('bob', 2) |
| 339 |
>>> bob4 = Record('bob', 4) |
| 340 |
>>> bob2 == bob4 |
| 341 |
True |
| 342 |
>>> bob2 < bob4 # <-- Here's the problem. BAD! |
| 343 |
True |
| 344 |
|
| 345 |
In the above example, `bob2` and `bob4` are equal to each other while `bob2` is |
| 346 |
also strictly less than `bob4`. The `Record` type therefore does not have a |
| 347 |
`total ordering`_. In pseudocode the three requirements for a `total ordering`_ |
| 348 |
are: |
| 349 |
|
| 350 |
I. If ``a <= b and b <= a`` then ``a == b``. |
| 351 |
|
| 352 |
II. And if ``a <= b and b <= c`` then ``a <= c``. |
| 353 |
|
| 354 |
III. And ``a <= b or b <= a``. |
| 355 |
|
| 356 |
Intuitively, a `total ordering`_ is best understood through integer and string |
| 357 |
types. Each of these common types defines a `total ordering`_ and can be used |
| 358 |
for comparisons in :doc:`Sorted Containers<index>`. Of the built-in types in |
| 359 |
Python, these have a `total ordering`_: |
| 360 |
|
| 361 |
1. Integers |
| 362 |
|
| 363 |
2. Strings and bytes. |
| 364 |
|
| 365 |
3. All foating-point numbers except ``float('nan')``. |
| 366 |
|
| 367 |
4. Sequences like `list` and `tuple` of values with a total ordering. |
| 368 |
|
| 369 |
There are also some built-in Python types and values which lack a total |
| 370 |
ordering: |
| 371 |
|
| 372 |
1. Sets and frozensets (not a total ordering). |
| 373 |
|
| 374 |
2. ``float('nan')`` (not a total ordering). |
| 375 |
|
| 376 |
3. Mapping types (not comparable, changed in Python 3). |
| 377 |
|
| 378 |
The best way to fix the `Record` type is to define equality and comparison in |
| 379 |
terms of the same fields. |
| 380 |
|
| 381 |
>>> class Record(object): |
| 382 |
... def __init__(self, name, rank): |
| 383 |
... self.name = name |
| 384 |
... self.rank = rank |
| 385 |
... def _cmp_key(self): |
| 386 |
... return (self.rank, self.name) |
| 387 |
... def __eq__(self, other): |
| 388 |
... return self._cmp_key() == other._cmp_key() |
| 389 |
... def __lt__(self, other): |
| 390 |
... return self._cmp_key() < other._cmp_key() |
| 391 |
|
| 392 |
The example above uses a comparison-key method named `_cmp_key` and the |
| 393 |
lexicographical ordering semantics of tuples to define equality and comparison |
| 394 |
in terms of the `rank` and `name` fields. It would also be possible to omit the |
| 395 |
`Record.__lt__` method and instead use a key-function which called |
| 396 |
`record._cmp_key()`. But the key-function will take more memory and be slower |
| 397 |
as it uses a :class:`SortedKeyList` which stores a reference to the key for |
| 398 |
every value. |
| 399 |
|
| 400 |
The `Record` example above is complicated by equality defined as those objects |
| 401 |
with equal names. When using equality inherited from `object`, that is, defined |
| 402 |
in terms of instance identity, the situation is simplified. For example: |
| 403 |
|
| 404 |
>>> class Record(object): |
| 405 |
... def __init__(self, name, rank): |
| 406 |
... self.name = name |
| 407 |
... self.rank = rank |
| 408 |
... def __lt__(self, other): |
| 409 |
... return self.rank < other.rank |
| 410 |
|
| 411 |
The `Record` type now can be stored in :class:`SortedList` because equality |
| 412 |
based on instance identity guarantees the `rank` attributes are equal so long |
| 413 |
as its value has a `total ordering`_. |
| 414 |
|
| 415 |
>>> alice1 = Record('alice', 1) |
| 416 |
>>> bob2 = Record('bob', 2) |
| 417 |
>>> carol3 = Record('carol', 3) |
| 418 |
>>> bob4 = Record('bob', 4) |
| 419 |
>>> bob2 != bob4 # <-- Different instances, so unequal. GOOD! |
| 420 |
True |
| 421 |
>>> sl = SortedList([alice1, bob2, carol3, bob4]) |
| 422 |
>>> bob2 in sl |
| 423 |
True |
| 424 |
>>> bob4 in sl |
| 425 |
True |
| 426 |
|
| 427 |
The above example displays that all three requirements are followed: |
| 428 |
|
| 429 |
1. The comparison key, `rank`, is an integer, which has a `total ordering`_. |
| 430 |
|
| 431 |
2. The comparison key does not change while the value is stored in the sorted |
| 432 |
container. |
| 433 |
|
| 434 |
3. Equal `Record` instances have equal `rank` attributes based on instance |
| 435 |
identity. |
| 436 |
|
| 437 |
These examples can be summarized in two pieces of advice: |
| 438 |
|
| 439 |
1. If the data type defines its own equality, that is ``__eq__``, then make |
| 440 |
sure the comparison methods or key-function define a `total ordering`_ and |
| 441 |
equal values have equal comparison keys. |
| 442 |
|
| 443 |
2. If the data type does not define equality then it inherits equality from |
| 444 |
`object` and uses instance identity. Compare objects using comparison |
| 445 |
methods like ``__lt__`` or the key-function. The compared values must have a |
| 446 |
`total ordering`_. |
| 447 |
|
| 448 |
Another invalid use case of :class:`SortedKeyList` occurs when the key-function |
| 449 |
returns a different comparison key for a given value while the value is stored |
| 450 |
in the sorted container. |
| 451 |
|
| 452 |
>>> from random import random |
| 453 |
>>> key_func = lambda value: random() |
| 454 |
>>> sl = SortedList([1, 2, 3, 4, 5], key=key_func) |
| 455 |
>>> # ^-- Corrupt sorted list. |
| 456 |
>>> 3 in sl |
| 457 |
False |
| 458 |
>>> key_func(1) == key_func(1) # <-- Here's the problem. BAD! |
| 459 |
False |
| 460 |
|
| 461 |
The example above violates two requirements of sorted lists: equal values must |
| 462 |
have equal keys and the key function must return the same key for the given |
| 463 |
value while the value is stored in the sorted container. The `random` |
| 464 |
key-function does not reliably return the same key for a given value. The order |
| 465 |
of values in a sorted container can be made arbitrary and reliable by changing |
| 466 |
the key-function like so: |
| 467 |
|
| 468 |
>>> from random import seed |
| 469 |
>>> def key_func(value): |
| 470 |
... "Key-function for arbitrary but reliable order." |
| 471 |
... seed(value) |
| 472 |
... return random() |
| 473 |
|
| 474 |
Another way the problem above manifests itself is when the comparison key of an |
| 475 |
object is mutated while the object is stored in the :class:`SortedList`. Using |
| 476 |
the `Record` definition from above: |
| 477 |
|
| 478 |
>>> class Record(object): |
| 479 |
... def __init__(self, name, rank): |
| 480 |
... self.name = name |
| 481 |
... self.rank = rank |
| 482 |
... def __lt__(self, other): |
| 483 |
... return self.rank < other.rank |
| 484 |
>>> alice1 = Record('alice', 1) |
| 485 |
>>> bob2 = Record('bob', 2) |
| 486 |
>>> carol3 = Record('carol', 3) |
| 487 |
>>> sl = SortedList([alice1, bob2, carol3]) |
| 488 |
>>> bob2 in sl |
| 489 |
True |
| 490 |
|
| 491 |
Python objects are typically mutable so while the above example works and is |
| 492 |
correct, there's nothing preventing a modification to the `rank` of a `Record`. |
| 493 |
If the `rank` is modified while the `Record` instance is stored in the |
| 494 |
:class:`SortedList`, then the container is corrupted. |
| 495 |
|
| 496 |
>>> bob2.rank = 20 # <-- Here's the problem. BAD! |
| 497 |
>>> bob2 in sl |
| 498 |
False |
| 499 |
|
| 500 |
The `Record` instance `bob2` can no longer be found in the :class:`SortedList` |
| 501 |
because modifying the `rank` changed its sort order position without updating |
| 502 |
its position in `sl`. To modify the sorted order position, :func:`remove |
| 503 |
<SortedList.remove>` the value, update it, and then :func:`add |
| 504 |
<SortedList.add>` the value back again. |
| 505 |
|
| 506 |
Similar limitations also apply to Python's `dict` data type which can be |
| 507 |
corrupted by modifying the hash of a key while the item is stored in the |
| 508 |
`dict`. The hashing protocol also requires that equal keys have equal hashes. |
| 509 |
|
| 510 |
One final caveat: indexing a sorted list is fast but not as fast as indexing |
| 511 |
Python's built-in list data type. The runtime complexity for indexing a sorted |
| 512 |
list is `O(log(n))` while it is `O(1)` for Python's built-in list data type. |
| 513 |
Indexing a sorted list requires building and maintaining a positional index |
| 514 |
which is not built if not necessary. The index is fast and light on memory |
| 515 |
overhead but avoid positional indexing if able. Indexing at the front or back, |
| 516 |
indexes like `0` and `-1`, is optimized and will not require the positional |
| 517 |
index. |
| 518 |
|
| 519 |
.. _`total ordering`: https://en.wikipedia.org/wiki/Total_order |
| 520 |
|
| 521 |
|
| 522 |
Sorted Dict |
| 523 |
----------- |
| 524 |
|
| 525 |
Built atop Python's built-in `dict` data type and :class:`SortedList` is the |
| 526 |
mutable mapping data type :class:`SortedDict`. Sorted dict keys are maintained |
| 527 |
in sorted order. The design of :class:`SortedDict` is simple: sorted dict |
| 528 |
inherits from `dict` to store items and maintains a sorted list of |
| 529 |
keys. :class:`SortedDict` keys must be hashable and comparable. The hash and |
| 530 |
total ordering of keys must not change while they are stored in the |
| 531 |
:class:`SortedDict`. |
| 532 |
|
| 533 |
>>> from sortedcontainers import SortedDict |
| 534 |
>>> sd = SortedDict() |
| 535 |
|
| 536 |
Items may be added to a :class:`SortedDict` using |
| 537 |
:func:`SortedDict.__setitem__`, :func:`SortedDict.update` or |
| 538 |
:func:`SortedDict.setdefault`. When doing so, the keys remain sorted. |
| 539 |
|
| 540 |
>>> sd['e'] = 5 |
| 541 |
>>> sd['b'] = 2 |
| 542 |
>>> sd |
| 543 |
SortedDict({'b': 2, 'e': 5}) |
| 544 |
>>> sd.update({'d': 4, 'c': 3}) |
| 545 |
>>> sd |
| 546 |
SortedDict({'b': 2, 'c': 3, 'd': 4, 'e': 5}) |
| 547 |
>>> sd.setdefault('a', 1) |
| 548 |
1 |
| 549 |
>>> sd |
| 550 |
SortedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}) |
| 551 |
|
| 552 |
Several methods may be used to remove items by key or by index. The methods |
| 553 |
:func:`SortedDict.__delitem__` and :func:`SortedDict.pop` remove items by |
| 554 |
key. And the method :func:`SortedDict.popitem` removes items by index. |
| 555 |
|
| 556 |
>>> del sd['d'] |
| 557 |
>>> sd.pop('c') |
| 558 |
3 |
| 559 |
>>> sd.popitem(index=-1) |
| 560 |
('e', 5) |
| 561 |
>>> sd |
| 562 |
SortedDict({'a': 1, 'b': 2}) |
| 563 |
|
| 564 |
Because :class:`SortedDict` uses both `dict` and :class:`SortedList`, there are |
| 565 |
many methods for looking up keys from each type. The mapping interface supports |
| 566 |
:func:`SortedDict.__getitem__`, :func:`SortedDict.__contains__`, |
| 567 |
:func:`SortedDict.get`, and :func:`SortedDict.peekitem`. |
| 568 |
|
| 569 |
>>> sd['b'] |
| 570 |
2 |
| 571 |
>>> 'c' in sd |
| 572 |
False |
| 573 |
>>> sd.get('z') is None |
| 574 |
True |
| 575 |
>>> sd.peekitem(index=-1) |
| 576 |
('b', 2) |
| 577 |
|
| 578 |
The sequence interface supports the same lookup methods as those provided by |
| 579 |
:class:`SortedList`. |
| 580 |
|
| 581 |
>>> sd.bisect_right('b') |
| 582 |
2 |
| 583 |
>>> sd.index('a') |
| 584 |
0 |
| 585 |
>>> list(sd.irange('a', 'z')) |
| 586 |
['a', 'b'] |
| 587 |
|
| 588 |
The keys, items, and values views also support both set semantics and sequence |
| 589 |
semantics with optimized methods for lookups by index. |
| 590 |
|
| 591 |
>>> keys = sd.keys() |
| 592 |
>>> keys[0] |
| 593 |
'a' |
| 594 |
>>> items = sd.items() |
| 595 |
>>> items[-1] |
| 596 |
('b', 2) |
| 597 |
>>> values = sd.values() |
| 598 |
>>> values[:] |
| 599 |
[1, 2] |
| 600 |
|
| 601 |
The :class:`SortedDict` initializer supports one additional position argument. |
| 602 |
The positional argument must come before any sequences, mappings, or keyword |
| 603 |
arguments used to initialize the items in a :class:`SortedDict`. The first |
| 604 |
positional argument is an optional callable key-function used to extract a |
| 605 |
comparison key from the keys of the :class:`SortedDict`. For example, to |
| 606 |
construct a :class:`SortedDict` with integer keys in descending order: |
| 607 |
|
| 608 |
>>> sd = SortedDict(neg, enumerate('abc', start=1)) |
| 609 |
>>> sd |
| 610 |
SortedDict(<built-in function neg>, {3: 'c', 2: 'b', 1: 'a'}) |
| 611 |
>>> keys = sd.keys() |
| 612 |
>>> list(keys) |
| 613 |
[3, 2, 1] |
| 614 |
|
| 615 |
Because :class:`SortedDict` inherits from `dict`, the `__missing__` method can |
| 616 |
be used to give missing keys a default value. Customizing the `__missing__` |
| 617 |
method creates a kind of `defaultdict` like that in the `collections` module. |
| 618 |
|
| 619 |
>>> class DefaultSortedDict(SortedDict): |
| 620 |
... def __missing__(self, key): |
| 621 |
... return 0 |
| 622 |
>>> dsd = DefaultSortedDict() |
| 623 |
>>> dsd['z'] |
| 624 |
0 |
| 625 |
|
| 626 |
Refer to the :doc:`Sorted Dict documentation<sorteddict>` for additional |
| 627 |
parameters, more examples, and descriptions of runtime complexity. |
| 628 |
|
| 629 |
|
| 630 |
Sorted Set |
| 631 |
---------- |
| 632 |
|
| 633 |
Standing on the shoulder's of Python's built-in `set` data type and |
| 634 |
:class:`SortedList` is the mutable set data type :class:`SortedSet`. Sorted set |
| 635 |
values are maintained in sorted order. The design of :class:`SortedSet` is |
| 636 |
simple: sorted set uses Python's built-in `set` for set-operations and |
| 637 |
maintains a sorted list of values. Values stored in a :class:`SortedSet` must |
| 638 |
be hashable and comparable. The hash and total ordering of values must not |
| 639 |
change while they are stored in the :class:`SortedSet`. |
| 640 |
|
| 641 |
>>> from sortedcontainers import SortedSet |
| 642 |
>>> ss = SortedSet() |
| 643 |
|
| 644 |
:class:`SortedSet` implements optimized versions of the core mutable set |
| 645 |
methods: :func:`SortedSet.__contains__`, :func:`SortedSet.add`, |
| 646 |
:func:`SortedSet.update`, :func:`SortedSet.discard`, and the more strict |
| 647 |
:func:`SortedSet.remove`. |
| 648 |
|
| 649 |
>>> ss.add('c') |
| 650 |
>>> ss.add('a') |
| 651 |
>>> ss.add('b') |
| 652 |
>>> ss |
| 653 |
SortedSet(['a', 'b', 'c']) |
| 654 |
>>> 'c' in ss |
| 655 |
True |
| 656 |
>>> ss.discard('a') |
| 657 |
>>> ss.remove('b') |
| 658 |
>>> _ = ss.update('def') |
| 659 |
>>> ss |
| 660 |
SortedSet(['c', 'd', 'e', 'f']) |
| 661 |
|
| 662 |
:class:`SortedSet` also behaves like a sequence with |
| 663 |
:func:`SortedSet.__getitem__` and :func:`SortedSet.__reversed__` methods. And |
| 664 |
includes the mutable sequence methods :func:`SortedSet.__delitem__` and |
| 665 |
:func:`SortedSet.pop`. |
| 666 |
|
| 667 |
>>> ss[0] |
| 668 |
'c' |
| 669 |
>>> list(reversed(ss)) |
| 670 |
['f', 'e', 'd', 'c'] |
| 671 |
>>> del ss[0] |
| 672 |
>>> ss.pop(index=-1) |
| 673 |
'f' |
| 674 |
>>> ss |
| 675 |
SortedSet(['d', 'e']) |
| 676 |
|
| 677 |
Set-operation methods like :func:`SortedSet.difference`, |
| 678 |
:func:`SortedSet.intersection`, :func:`SortedSet.symmetric_difference`, and |
| 679 |
:func:`SortedSet.union`, as well as their in-place counterparts and operators |
| 680 |
are all supported. |
| 681 |
|
| 682 |
>>> abcd = SortedSet('abcd') |
| 683 |
>>> cdef = SortedSet('cdef') |
| 684 |
>>> abcd.difference(cdef) |
| 685 |
SortedSet(['a', 'b']) |
| 686 |
>>> abcd.intersection(cdef) |
| 687 |
SortedSet(['c', 'd']) |
| 688 |
>>> abcd.symmetric_difference(cdef) |
| 689 |
SortedSet(['a', 'b', 'e', 'f']) |
| 690 |
>>> abcd.union(cdef) |
| 691 |
SortedSet(['a', 'b', 'c', 'd', 'e', 'f']) |
| 692 |
>>> abcd | cdef |
| 693 |
SortedSet(['a', 'b', 'c', 'd', 'e', 'f']) |
| 694 |
>>> abcd |= cdef |
| 695 |
>>> abcd |
| 696 |
SortedSet(['a', 'b', 'c', 'd', 'e', 'f']) |
| 697 |
|
| 698 |
Several :class:`SortedList` methods are also exposed on :class:`SortedSet` |
| 699 |
objects like :func:`SortedList.bisect`, :func:`SortedList.index`, |
| 700 |
:func:`SortedList.irange`, and :func:`SortedList.islice` just as with |
| 701 |
:class:`SortedDict`. |
| 702 |
|
| 703 |
>>> ss = SortedSet('abcdef') |
| 704 |
>>> ss.bisect('d') |
| 705 |
4 |
| 706 |
>>> ss.index('f') |
| 707 |
5 |
| 708 |
>>> list(ss.irange('b', 'e')) |
| 709 |
['b', 'c', 'd', 'e'] |
| 710 |
>>> list(ss.islice(-3)) |
| 711 |
['d', 'e', 'f'] |
| 712 |
|
| 713 |
Like :class:`SortedList` an additional `key` parameter can be used to |
| 714 |
initialize the :class:`SortedSet` with a callable which is used to extract a |
| 715 |
comparison key. |
| 716 |
|
| 717 |
>>> ss = SortedSet([1, 2, 3], key=neg) |
| 718 |
>>> ss |
| 719 |
SortedSet([3, 2, 1], key=<built-in function neg>) |
| 720 |
|
| 721 |
Sorted set comparisons use subset and superset relations. Two sorted sets are |
| 722 |
equal if and only if every element of each sorted set is contained in the other |
| 723 |
(each is a subset of the other). A sorted set is less than another sorted set |
| 724 |
if and only if the first sorted set is a proper subset of the second sorted set |
| 725 |
(is a subset, but is not equal). A sorted set is greater than another sorted |
| 726 |
set if and only if the first sorted set is a proper superset of the second |
| 727 |
sorted set (is a superset, but is not equal). The comparison semantics of |
| 728 |
sorted sets do not define a total ordering. |
| 729 |
|
| 730 |
Refer to the :doc:`Sorted Set documentation<sortedset>` for additional |
| 731 |
parameters, more examples, and descriptions of runtime complexity. |
| 732 |
|
| 733 |
|
| 734 |
Migrating |
| 735 |
--------- |
| 736 |
|
| 737 |
The :doc:`performance comparison<performance>` page documents several |
| 738 |
alternative implementations of the sorted types described. Some of those |
| 739 |
projects have deprecated themselves and now recommend :doc:`Sorted |
| 740 |
Containers<index>` instead. When migrating from other projects, there are a |
| 741 |
couple of things to keep in mind. |
| 742 |
|
| 743 |
:doc:`Sorted Containers<index>` went through a major version change between |
| 744 |
version one and version two. The goal of the change was to adopt Python 3 |
| 745 |
semantics wherever possible: |
| 746 |
|
| 747 |
1. Several :class:`SortedList` methods now raise :exc:`NotImplementedError`: |
| 748 |
:func:`SortedList.__setitem__`, :func:`SortedList.append`, and |
| 749 |
:func:`SortedList.extend`. Use :func:`SortedList.add` or |
| 750 |
:func:`SortedList.update` instead. |
| 751 |
|
| 752 |
2. :class:`SortedDict` has adopted the Python 3 semantics of `dict` views as |
| 753 |
the default. The :func:`SortedDict.keys`, :func:`SortedDict.items`, and |
| 754 |
:func:`SortedDict.values` methods now return views with support for |
| 755 |
optimized indexing. The view objects also implement set and sequence |
| 756 |
protocol methods. Prefer using the :class:`SortedDict` methods directly for |
| 757 |
better performance. |
| 758 |
|
| 759 |
3. Some type and parameter names were changed. `SortedListWithKey` was renamed |
| 760 |
to `SortedKeyList` but an alias remains for compatibility. Several methods |
| 761 |
which accepted a `val` parameter now accept `value` for better readability. |
| 762 |
|
| 763 |
The :doc:`history` documents all the changes made in every version in the |
| 764 |
history of the project. The :ref:`Version 2<v2>` release notes detail all the |
| 765 |
changes made. |
| 766 |
|
| 767 |
The `blist`_ project remains the most similar as its API was the original |
| 768 |
inspiration for :doc:`Sorted Containers<index>`. The main difference has always |
| 769 |
been the :func:`SortedList.pop` method. The `blist`_ project pops the first |
| 770 |
element by default while :doc:`Sorted Containers<index>` pops the last element |
| 771 |
and matches the API of Python's built-in `list` data type. The sorted dict data |
| 772 |
type in `blist`_ also continues to use the old Python 2 semantics for `dict` |
| 773 |
views. |
| 774 |
|
| 775 |
The `bintrees`_ project now recommends using :doc:`Sorted Containers<index>` |
| 776 |
instead and has stopped development. The API differs significantly but the |
| 777 |
supported functionality is the same. The `Tree` object in `bintrees`_ is most |
| 778 |
similar to :class:`SortedDict`. All of the mapping methods and set methods are |
| 779 |
available using either :class:`SortedDict` or :class:`SortedKeysView`. The |
| 780 |
slicing methods and previous/successor iterator methods correspond to |
| 781 |
:func:`SortedDict.irange` and the heap methods correspond to indexing with |
| 782 |
views like :func:`SortedKeysView.__getitem__`. |
| 783 |
|
| 784 |
The `banyan`_ project has data types similar to :class:`SortedDict` and |
| 785 |
:class:`SortedSet`. Most methods have a direct counterpart in :doc:`Sorted |
| 786 |
Containers<index>`. But the frozen sorted dict and frozen sorted set data types |
| 787 |
have no direct comparison. The functionality of hashing can be implemented by |
| 788 |
inheriting and defining the `__hash__` method. Do so with care, because the |
| 789 |
instance is still mutable. The `banyan`_ project also supports tree |
| 790 |
augmentation which can be useful in implementing interval trees or segment |
| 791 |
trees. There is no support for tree argumentation in :doc:`Sorted |
| 792 |
Containers<index>`. |
| 793 |
|
| 794 |
.. _`blist`: https://pypi.org/project/blist/ |
| 795 |
.. _`bintrees`: https://pypi.org/project/bintrees/ |
| 796 |
.. _`banyan`: https://pypi.org/project/Banyan/ |