Advertisement
whiteshark05

SortedList

Mar 5th, 2023
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 49.99 KB | Software | 0 0
  1. import sys
  2. import traceback
  3.  
  4. # This is faster than PyRival's implementation of sortedlist
  5.  
  6. # Contains the following license
  7. # - https://github.com/grantjenks/python-sortedcontainers/
  8.  
  9. # Copyright 2014-2019 Grant Jenks
  10.  
  11. # Licensed under the Apache License, Version 2.0 (the "License");
  12. # you may not use this file except in compliance with the License.
  13. # You may obtain a copy of the License at
  14.  
  15. #     http://www.apache.org/licenses/LICENSE-2.0
  16.  
  17. # Unless required by applicable law or agreed to in writing, software
  18. # distributed under the License is distributed on an "AS IS" BASIS,
  19. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. # See the License for the specific language governing permissions and
  21. # limitations under the License.
  22.  
  23.  
  24.  
  25. """Sorted List
  26. ==============
  27.  
  28. :doc:`Sorted Containers<index>` is an Apache2 licensed Python sorted
  29. collections library, written in pure-Python, and fast as C-extensions. The
  30. :doc:`introduction<introduction>` is the best way to get started.
  31.  
  32. Sorted list implementations:
  33.  
  34. .. currentmodule:: sortedcontainers
  35.  
  36. * :class:`SortedList`
  37. * :class:`SortedKeyList`
  38.  
  39. """
  40. # pylint: disable=too-many-lines
  41.  
  42. import sys
  43. import traceback
  44.  
  45. from bisect import bisect_left, bisect_right, insort
  46. from itertools import chain, repeat, starmap
  47. from math import log2
  48. from operator import add, eq, ne, gt, ge, lt, le, iadd
  49. from textwrap import dedent
  50.  
  51. ###############################################################################
  52. # BEGIN Python 2/3 Shims
  53. ###############################################################################
  54.  
  55. try:
  56.     from collections.abc import Sequence, MutableSequence
  57. except ImportError:
  58.     from collections import Sequence, MutableSequence
  59.  
  60. from functools import wraps
  61. from sys import hexversion
  62.  
  63. if hexversion < 0x03000000:
  64.     from itertools import imap as map  # pylint: disable=redefined-builtin
  65.     from itertools import izip as zip  # pylint: disable=redefined-builtin
  66.     try:
  67.         from thread import get_ident
  68.     except ImportError:
  69.         from dummy_thread import get_ident
  70. else:
  71.     from functools import reduce
  72.     try:
  73.         from _thread import get_ident
  74.     except ImportError:
  75.         from _dummy_thread import get_ident
  76.  
  77.  
  78. def recursive_repr(fillvalue='...'):
  79.     "Decorator to make a repr function return fillvalue for a recursive call."
  80.     # pylint: disable=missing-docstring
  81.     # Copied from reprlib in Python 3
  82.     # https://hg.python.org/cpython/file/3.6/Lib/reprlib.py
  83.  
  84.     def decorating_function(user_function):
  85.         repr_running = set()
  86.  
  87.         @wraps(user_function)
  88.         def wrapper(self):
  89.             key = id(self), get_ident()
  90.             if key in repr_running:
  91.                 return fillvalue
  92.             repr_running.add(key)
  93.             try:
  94.                 result = user_function(self)
  95.             finally:
  96.                 repr_running.discard(key)
  97.             return result
  98.  
  99.         return wrapper
  100.  
  101.     return decorating_function
  102.  
  103. ###############################################################################
  104. # END Python 2/3 Shims
  105. ###############################################################################
  106.  
  107.  
  108. class SortedList(MutableSequence):
  109.     """Sorted list is a sorted mutable sequence.
  110.  
  111.    Sorted list values are maintained in sorted order.
  112.  
  113.    Sorted list values must be comparable. The total ordering of values must
  114.    not change while they are stored in the sorted list.
  115.  
  116.    Methods for adding values:
  117.  
  118.    * :func:`SortedList.add`
  119.    * :func:`SortedList.update`
  120.    * :func:`SortedList.__add__`
  121.    * :func:`SortedList.__iadd__`
  122.    * :func:`SortedList.__mul__`
  123.    * :func:`SortedList.__imul__`
  124.  
  125.    Methods for removing values:
  126.  
  127.    * :func:`SortedList.clear`
  128.    * :func:`SortedList.discard`
  129.    * :func:`SortedList.remove`
  130.    * :func:`SortedList.pop`
  131.    * :func:`SortedList.__delitem__`
  132.  
  133.    Methods for looking up values:
  134.  
  135.    * :func:`SortedList.bisect_left`
  136.    * :func:`SortedList.bisect_right`
  137.    * :func:`SortedList.count`
  138.    * :func:`SortedList.index`
  139.    * :func:`SortedList.__contains__`
  140.    * :func:`SortedList.__getitem__`
  141.  
  142.    Methods for iterating values:
  143.  
  144.    * :func:`SortedList.irange`
  145.    * :func:`SortedList.islice`
  146.    * :func:`SortedList.__iter__`
  147.    * :func:`SortedList.__reversed__`
  148.  
  149.    Methods for miscellany:
  150.  
  151.    * :func:`SortedList.copy`
  152.    * :func:`SortedList.__len__`
  153.    * :func:`SortedList.__repr__`
  154.    * :func:`SortedList._check`
  155.    * :func:`SortedList._reset`
  156.  
  157.    Sorted lists use lexicographical ordering semantics when compared to other
  158.    sequences.
  159.  
  160.    Some methods of mutable sequences are not supported and will raise
  161.    not-implemented error.
  162.  
  163.    """
  164.     DEFAULT_LOAD_FACTOR = 1000
  165.  
  166.  
  167.     def __init__(self, iterable=None, key=None):
  168.         """Initialize sorted list instance.
  169.  
  170.        Optional `iterable` argument provides an initial iterable of values to
  171.        initialize the sorted list.
  172.  
  173.        Runtime complexity: `O(n*log(n))`
  174.  
  175.        >>> sl = SortedList()
  176.        >>> sl
  177.        SortedList([])
  178.        >>> sl = SortedList([3, 1, 2, 5, 4])
  179.        >>> sl
  180.        SortedList([1, 2, 3, 4, 5])
  181.  
  182.        :param iterable: initial values (optional)
  183.  
  184.        """
  185.         assert key is None
  186.         self._len = 0
  187.         self._load = self.DEFAULT_LOAD_FACTOR
  188.         self._lists = []
  189.         self._maxes = []
  190.         self._index = []
  191.         self._offset = 0
  192.  
  193.         if iterable is not None:
  194.             self._update(iterable)
  195.  
  196.  
  197.     def __new__(cls, iterable=None, key=None):
  198.         """Create new sorted list or sorted-key list instance.
  199.  
  200.        Optional `key`-function argument will return an instance of subtype
  201.        :class:`SortedKeyList`.
  202.  
  203.        >>> sl = SortedList()
  204.        >>> isinstance(sl, SortedList)
  205.        True
  206.        >>> sl = SortedList(key=lambda x: -x)
  207.        >>> isinstance(sl, SortedList)
  208.        True
  209.        >>> isinstance(sl, SortedKeyList)
  210.        True
  211.  
  212.        :param iterable: initial values (optional)
  213.        :param key: function used to extract comparison key (optional)
  214.        :return: sorted list or sorted-key list instance
  215.  
  216.        """
  217.         # pylint: disable=unused-argument
  218.         if key is None:
  219.             return object.__new__(cls)
  220.         else:
  221.             if cls is SortedList:
  222.                 return object.__new__(SortedKeyList)
  223.             else:
  224.                 raise TypeError('inherit SortedKeyList for key argument')
  225.  
  226.  
  227.     @property
  228.     def key(self):  # pylint: disable=useless-return
  229.         """Function used to extract comparison key from values.
  230.  
  231.        Sorted list compares values directly so the key function is none.
  232.  
  233.        """
  234.         return None
  235.  
  236.  
  237.     def _reset(self, load):
  238.         """Reset sorted list load factor.
  239.  
  240.        The `load` specifies the load-factor of the list. The default load
  241.        factor of 1000 works well for lists from tens to tens-of-millions of
  242.        values. Good practice is to use a value that is the cube root of the
  243.        list size. With billions of elements, the best load factor depends on
  244.        your usage. It's best to leave the load factor at the default until you
  245.        start benchmarking.
  246.  
  247.        See :doc:`implementation` and :doc:`performance-scale` for more
  248.        information.
  249.  
  250.        Runtime complexity: `O(n)`
  251.  
  252.        :param int load: load-factor for sorted list sublists
  253.  
  254.        """
  255.         values = reduce(iadd, self._lists, [])
  256.         self._clear()
  257.         self._load = load
  258.         self._update(values)
  259.  
  260.  
  261.     def clear(self):
  262.         """Remove all values from sorted list.
  263.  
  264.        Runtime complexity: `O(n)`
  265.  
  266.        """
  267.         self._len = 0
  268.         del self._lists[:]
  269.         del self._maxes[:]
  270.         del self._index[:]
  271.         self._offset = 0
  272.  
  273.     _clear = clear
  274.  
  275.  
  276.     def add(self, value):
  277.         """Add `value` to sorted list.
  278.  
  279.        Runtime complexity: `O(log(n))` -- approximate.
  280.  
  281.        >>> sl = SortedList()
  282.        >>> sl.add(3)
  283.        >>> sl.add(1)
  284.        >>> sl.add(2)
  285.        >>> sl
  286.        SortedList([1, 2, 3])
  287.  
  288.        :param value: value to add to sorted list
  289.  
  290.        """
  291.         _lists = self._lists
  292.         _maxes = self._maxes
  293.  
  294.         if _maxes:
  295.             pos = bisect_right(_maxes, value)
  296.  
  297.             if pos == len(_maxes):
  298.                 pos -= 1
  299.                 _lists[pos].append(value)
  300.                 _maxes[pos] = value
  301.             else:
  302.                 insort(_lists[pos], value)
  303.  
  304.             self._expand(pos)
  305.         else:
  306.             _lists.append([value])
  307.             _maxes.append(value)
  308.  
  309.         self._len += 1
  310.  
  311.  
  312.     def _expand(self, pos):
  313.         """Split sublists with length greater than double the load-factor.
  314.  
  315.        Updates the index when the sublist length is less than double the load
  316.        level. This requires incrementing the nodes in a traversal from the
  317.        leaf node to the root. For an example traversal see
  318.        ``SortedList._loc``.
  319.  
  320.        """
  321.         _load = self._load
  322.         _lists = self._lists
  323.         _index = self._index
  324.  
  325.         if len(_lists[pos]) > (_load << 1):
  326.             _maxes = self._maxes
  327.  
  328.             _lists_pos = _lists[pos]
  329.             half = _lists_pos[_load:]
  330.             del _lists_pos[_load:]
  331.             _maxes[pos] = _lists_pos[-1]
  332.  
  333.             _lists.insert(pos + 1, half)
  334.             _maxes.insert(pos + 1, half[-1])
  335.  
  336.             del _index[:]
  337.         else:
  338.             if _index:
  339.                 child = self._offset + pos
  340.                 while child:
  341.                     _index[child] += 1
  342.                     child = (child - 1) >> 1
  343.                 _index[0] += 1
  344.  
  345.  
  346.     def update(self, iterable):
  347.         """Update sorted list by adding all values from `iterable`.
  348.  
  349.        Runtime complexity: `O(k*log(n))` -- approximate.
  350.  
  351.        >>> sl = SortedList()
  352.        >>> sl.update([3, 1, 2])
  353.        >>> sl
  354.        SortedList([1, 2, 3])
  355.  
  356.        :param iterable: iterable of values to add
  357.  
  358.        """
  359.         _lists = self._lists
  360.         _maxes = self._maxes
  361.         values = sorted(iterable)
  362.  
  363.         if _maxes:
  364.             if len(values) * 4 >= self._len:
  365.                 _lists.append(values)
  366.                 values = reduce(iadd, _lists, [])
  367.                 values.sort()
  368.                 self._clear()
  369.             else:
  370.                 _add = self.add
  371.                 for val in values:
  372.                     _add(val)
  373.                 return
  374.  
  375.         _load = self._load
  376.         _lists.extend(values[pos:(pos + _load)]
  377.                       for pos in range(0, len(values), _load))
  378.         _maxes.extend(sublist[-1] for sublist in _lists)
  379.         self._len = len(values)
  380.         del self._index[:]
  381.  
  382.     _update = update
  383.  
  384.  
  385.     def __contains__(self, value):
  386.         """Return true if `value` is an element of the sorted list.
  387.  
  388.        ``sl.__contains__(value)`` <==> ``value in sl``
  389.  
  390.        Runtime complexity: `O(log(n))`
  391.  
  392.        >>> sl = SortedList([1, 2, 3, 4, 5])
  393.        >>> 3 in sl
  394.        True
  395.  
  396.        :param value: search for value in sorted list
  397.        :return: true if `value` in sorted list
  398.  
  399.        """
  400.         _maxes = self._maxes
  401.  
  402.         if not _maxes:
  403.             return False
  404.  
  405.         pos = bisect_left(_maxes, value)
  406.  
  407.         if pos == len(_maxes):
  408.             return False
  409.  
  410.         _lists = self._lists
  411.         idx = bisect_left(_lists[pos], value)
  412.  
  413.         return _lists[pos][idx] == value
  414.  
  415.  
  416.     def discard(self, value):
  417.         """Remove `value` from sorted list if it is a member.
  418.  
  419.        If `value` is not a member, do nothing.
  420.  
  421.        Runtime complexity: `O(log(n))` -- approximate.
  422.  
  423.        >>> sl = SortedList([1, 2, 3, 4, 5])
  424.        >>> sl.discard(5)
  425.        >>> sl.discard(0)
  426.        >>> sl == [1, 2, 3, 4]
  427.        True
  428.  
  429.        :param value: `value` to discard from sorted list
  430.  
  431.        """
  432.         _maxes = self._maxes
  433.  
  434.         if not _maxes:
  435.             return
  436.  
  437.         pos = bisect_left(_maxes, value)
  438.  
  439.         if pos == len(_maxes):
  440.             return
  441.  
  442.         _lists = self._lists
  443.         idx = bisect_left(_lists[pos], value)
  444.  
  445.         if _lists[pos][idx] == value:
  446.             self._delete(pos, idx)
  447.  
  448.  
  449.     def remove(self, value):
  450.         """Remove `value` from sorted list; `value` must be a member.
  451.  
  452.        If `value` is not a member, raise ValueError.
  453.  
  454.        Runtime complexity: `O(log(n))` -- approximate.
  455.  
  456.        >>> sl = SortedList([1, 2, 3, 4, 5])
  457.        >>> sl.remove(5)
  458.        >>> sl == [1, 2, 3, 4]
  459.        True
  460.        >>> sl.remove(0)
  461.        Traceback (most recent call last):
  462.          ...
  463.        ValueError: 0 not in list
  464.  
  465.        :param value: `value` to remove from sorted list
  466.        :raises ValueError: if `value` is not in sorted list
  467.  
  468.        """
  469.         _maxes = self._maxes
  470.  
  471.         if not _maxes:
  472.             raise ValueError('{0!r} not in list'.format(value))
  473.  
  474.         pos = bisect_left(_maxes, value)
  475.  
  476.         if pos == len(_maxes):
  477.             raise ValueError('{0!r} not in list'.format(value))
  478.  
  479.         _lists = self._lists
  480.         idx = bisect_left(_lists[pos], value)
  481.  
  482.         if _lists[pos][idx] == value:
  483.             self._delete(pos, idx)
  484.         else:
  485.             raise ValueError('{0!r} not in list'.format(value))
  486.  
  487.  
  488.     def _delete(self, pos, idx):
  489.         """Delete value at the given `(pos, idx)`.
  490.  
  491.        Combines lists that are less than half the load level.
  492.  
  493.        Updates the index when the sublist length is more than half the load
  494.        level. This requires decrementing the nodes in a traversal from the
  495.        leaf node to the root. For an example traversal see
  496.        ``SortedList._loc``.
  497.  
  498.        :param int pos: lists index
  499.        :param int idx: sublist index
  500.  
  501.        """
  502.         _lists = self._lists
  503.         _maxes = self._maxes
  504.         _index = self._index
  505.  
  506.         _lists_pos = _lists[pos]
  507.  
  508.         del _lists_pos[idx]
  509.         self._len -= 1
  510.  
  511.         len_lists_pos = len(_lists_pos)
  512.  
  513.         if len_lists_pos > (self._load >> 1):
  514.             _maxes[pos] = _lists_pos[-1]
  515.  
  516.             if _index:
  517.                 child = self._offset + pos
  518.                 while child > 0:
  519.                     _index[child] -= 1
  520.                     child = (child - 1) >> 1
  521.                 _index[0] -= 1
  522.         elif len(_lists) > 1:
  523.             if not pos:
  524.                 pos += 1
  525.  
  526.             prev = pos - 1
  527.             _lists[prev].extend(_lists[pos])
  528.             _maxes[prev] = _lists[prev][-1]
  529.  
  530.             del _lists[pos]
  531.             del _maxes[pos]
  532.             del _index[:]
  533.  
  534.             self._expand(prev)
  535.         elif len_lists_pos:
  536.             _maxes[pos] = _lists_pos[-1]
  537.         else:
  538.             del _lists[pos]
  539.             del _maxes[pos]
  540.             del _index[:]
  541.  
  542.  
  543.     def _loc(self, pos, idx):
  544.         """Convert an index pair (lists index, sublist index) into a single
  545.        index number that corresponds to the position of the value in the
  546.        sorted list.
  547.  
  548.        Many queries require the index be built. Details of the index are
  549.        described in ``SortedList._build_index``.
  550.  
  551.        Indexing requires traversing the tree from a leaf node to the root. The
  552.        parent of each node is easily computable at ``(pos - 1) // 2``.
  553.  
  554.        Left-child nodes are always at odd indices and right-child nodes are
  555.        always at even indices.
  556.  
  557.        When traversing up from a right-child node, increment the total by the
  558.        left-child node.
  559.  
  560.        The final index is the sum from traversal and the index in the sublist.
  561.  
  562.        For example, using the index from ``SortedList._build_index``::
  563.  
  564.            _index = 14 5 9 3 2 4 5
  565.            _offset = 3
  566.  
  567.        Tree::
  568.  
  569.                 14
  570.              5      9
  571.            3   2  4   5
  572.  
  573.        Converting an index pair (2, 3) into a single index involves iterating
  574.        like so:
  575.  
  576.        1. Starting at the leaf node: offset + alpha = 3 + 2 = 5. We identify
  577.           the node as a left-child node. At such nodes, we simply traverse to
  578.           the parent.
  579.  
  580.        2. At node 9, position 2, we recognize the node as a right-child node
  581.           and accumulate the left-child in our total. Total is now 5 and we
  582.           traverse to the parent at position 0.
  583.  
  584.        3. Iteration ends at the root.
  585.  
  586.        The index is then the sum of the total and sublist index: 5 + 3 = 8.
  587.  
  588.        :param int pos: lists index
  589.        :param int idx: sublist index
  590.        :return: index in sorted list
  591.  
  592.        """
  593.         if not pos:
  594.             return idx
  595.  
  596.         _index = self._index
  597.  
  598.         if not _index:
  599.             self._build_index()
  600.  
  601.         total = 0
  602.  
  603.         # Increment pos to point in the index to len(self._lists[pos]).
  604.  
  605.         pos += self._offset
  606.  
  607.         # Iterate until reaching the root of the index tree at pos = 0.
  608.  
  609.         while pos:
  610.  
  611.             # Right-child nodes are at odd indices. At such indices
  612.             # account the total below the left child node.
  613.  
  614.             if not pos & 1:
  615.                 total += _index[pos - 1]
  616.  
  617.             # Advance pos to the parent node.
  618.  
  619.             pos = (pos - 1) >> 1
  620.  
  621.         return total + idx
  622.  
  623.  
  624.     def _pos(self, idx):
  625.         """Convert an index into an index pair (lists index, sublist index)
  626.        that can be used to access the corresponding lists position.
  627.  
  628.        Many queries require the index be built. Details of the index are
  629.        described in ``SortedList._build_index``.
  630.  
  631.        Indexing requires traversing the tree to a leaf node. Each node has two
  632.        children which are easily computable. Given an index, pos, the
  633.        left-child is at ``pos * 2 + 1`` and the right-child is at ``pos * 2 +
  634.        2``.
  635.  
  636.        When the index is less than the left-child, traversal moves to the
  637.        left sub-tree. Otherwise, the index is decremented by the left-child
  638.        and traversal moves to the right sub-tree.
  639.  
  640.        At a child node, the indexing pair is computed from the relative
  641.        position of the child node as compared with the offset and the remaining
  642.        index.
  643.  
  644.        For example, using the index from ``SortedList._build_index``::
  645.  
  646.            _index = 14 5 9 3 2 4 5
  647.            _offset = 3
  648.  
  649.        Tree::
  650.  
  651.                 14
  652.              5      9
  653.            3   2  4   5
  654.  
  655.        Indexing position 8 involves iterating like so:
  656.  
  657.        1. Starting at the root, position 0, 8 is compared with the left-child
  658.           node (5) which it is greater than. When greater the index is
  659.           decremented and the position is updated to the right child node.
  660.  
  661.        2. At node 9 with index 3, we again compare the index to the left-child
  662.           node with value 4. Because the index is the less than the left-child
  663.           node, we simply traverse to the left.
  664.  
  665.        3. At node 4 with index 3, we recognize that we are at a leaf node and
  666.           stop iterating.
  667.  
  668.        4. To compute the sublist index, we subtract the offset from the index
  669.           of the leaf node: 5 - 3 = 2. To compute the index in the sublist, we
  670.           simply use the index remaining from iteration. In this case, 3.
  671.  
  672.        The final index pair from our example is (2, 3) which corresponds to
  673.        index 8 in the sorted list.
  674.  
  675.        :param int idx: index in sorted list
  676.        :return: (lists index, sublist index) pair
  677.  
  678.        """
  679.         if idx < 0:
  680.             last_len = len(self._lists[-1])
  681.  
  682.             if (-idx) <= last_len:
  683.                 return len(self._lists) - 1, last_len + idx
  684.  
  685.             idx += self._len
  686.  
  687.             if idx < 0:
  688.                 raise IndexError('list index out of range')
  689.         elif idx >= self._len:
  690.             raise IndexError('list index out of range')
  691.  
  692.         if idx < len(self._lists[0]):
  693.             return 0, idx
  694.  
  695.         _index = self._index
  696.  
  697.         if not _index:
  698.             self._build_index()
  699.  
  700.         pos = 0
  701.         child = 1
  702.         len_index = len(_index)
  703.  
  704.         while child < len_index:
  705.             index_child = _index[child]
  706.  
  707.             if idx < index_child:
  708.                 pos = child
  709.             else:
  710.                 idx -= index_child
  711.                 pos = child + 1
  712.  
  713.             child = (pos << 1) + 1
  714.  
  715.         return (pos - self._offset, idx)
  716.  
  717.  
  718.     def _build_index(self):
  719.         """Build a positional index for indexing the sorted list.
  720.  
  721.        Indexes are represented as binary trees in a dense array notation
  722.        similar to a binary heap.
  723.  
  724.        For example, given a lists representation storing integers::
  725.  
  726.            0: [1, 2, 3]
  727.            1: [4, 5]
  728.            2: [6, 7, 8, 9]
  729.            3: [10, 11, 12, 13, 14]
  730.  
  731.        The first transformation maps the sub-lists by their length. The
  732.        first row of the index is the length of the sub-lists::
  733.  
  734.            0: [3, 2, 4, 5]
  735.  
  736.        Each row after that is the sum of consecutive pairs of the previous
  737.        row::
  738.  
  739.            1: [5, 9]
  740.            2: [14]
  741.  
  742.        Finally, the index is built by concatenating these lists together::
  743.  
  744.            _index = [14, 5, 9, 3, 2, 4, 5]
  745.  
  746.        An offset storing the start of the first row is also stored::
  747.  
  748.            _offset = 3
  749.  
  750.        When built, the index can be used for efficient indexing into the list.
  751.        See the comment and notes on ``SortedList._pos`` for details.
  752.  
  753.        """
  754.         row0 = list(map(len, self._lists))
  755.  
  756.         if len(row0) == 1:
  757.             self._index[:] = row0
  758.             self._offset = 0
  759.             return
  760.  
  761.         head = iter(row0)
  762.         tail = iter(head)
  763.         row1 = list(starmap(add, zip(head, tail)))
  764.  
  765.         if len(row0) & 1:
  766.             row1.append(row0[-1])
  767.  
  768.         if len(row1) == 1:
  769.             self._index[:] = row1 + row0
  770.             self._offset = 1
  771.             return
  772.  
  773.         size = 2 ** (int(log2(len(row1) - 1)) + 1)
  774.         row1.extend(repeat(0, size - len(row1)))
  775.         tree = [row0, row1]
  776.  
  777.         while len(tree[-1]) > 1:
  778.             head = iter(tree[-1])
  779.             tail = iter(head)
  780.             row = list(starmap(add, zip(head, tail)))
  781.             tree.append(row)
  782.  
  783.         reduce(iadd, reversed(tree), self._index)
  784.         self._offset = size * 2 - 1
  785.  
  786.  
  787.     def __delitem__(self, index):
  788.         """Remove value at `index` from sorted list.
  789.  
  790.        ``sl.__delitem__(index)`` <==> ``del sl[index]``
  791.  
  792.        Supports slicing.
  793.  
  794.        Runtime complexity: `O(log(n))` -- approximate.
  795.  
  796.        >>> sl = SortedList('abcde')
  797.        >>> del sl[2]
  798.        >>> sl
  799.        SortedList(['a', 'b', 'd', 'e'])
  800.        >>> del sl[:2]
  801.        >>> sl
  802.        SortedList(['d', 'e'])
  803.  
  804.        :param index: integer or slice for indexing
  805.        :raises IndexError: if index out of range
  806.  
  807.        """
  808.         if isinstance(index, slice):
  809.             start, stop, step = index.indices(self._len)
  810.  
  811.             if step == 1 and start < stop:
  812.                 if start == 0 and stop == self._len:
  813.                     return self._clear()
  814.                 elif self._len <= 8 * (stop - start):
  815.                     values = self._getitem(slice(None, start))
  816.                     if stop < self._len:
  817.                         values += self._getitem(slice(stop, None))
  818.                     self._clear()
  819.                     return self._update(values)
  820.  
  821.             indices = range(start, stop, step)
  822.  
  823.             # Delete items from greatest index to least so
  824.             # that the indices remain valid throughout iteration.
  825.  
  826.             if step > 0:
  827.                 indices = reversed(indices)
  828.  
  829.             _pos, _delete = self._pos, self._delete
  830.  
  831.             for index in indices:
  832.                 pos, idx = _pos(index)
  833.                 _delete(pos, idx)
  834.         else:
  835.             pos, idx = self._pos(index)
  836.             self._delete(pos, idx)
  837.  
  838.  
  839.     def __getitem__(self, index):
  840.         """Lookup value at `index` in sorted list.
  841.  
  842.        ``sl.__getitem__(index)`` <==> ``sl[index]``
  843.  
  844.        Supports slicing.
  845.  
  846.        Runtime complexity: `O(log(n))` -- approximate.
  847.  
  848.        >>> sl = SortedList('abcde')
  849.        >>> sl[1]
  850.        'b'
  851.        >>> sl[-1]
  852.        'e'
  853.        >>> sl[2:5]
  854.        ['c', 'd', 'e']
  855.  
  856.        :param index: integer or slice for indexing
  857.        :return: value or list of values
  858.        :raises IndexError: if index out of range
  859.  
  860.        """
  861.         _lists = self._lists
  862.  
  863.         if isinstance(index, slice):
  864.             start, stop, step = index.indices(self._len)
  865.  
  866.             if step == 1 and start < stop:
  867.                 # Whole slice optimization: start to stop slices the whole
  868.                 # sorted list.
  869.  
  870.                 if start == 0 and stop == self._len:
  871.                     return reduce(iadd, self._lists, [])
  872.  
  873.                 start_pos, start_idx = self._pos(start)
  874.                 start_list = _lists[start_pos]
  875.                 stop_idx = start_idx + stop - start
  876.  
  877.                 # Small slice optimization: start index and stop index are
  878.                 # within the start list.
  879.  
  880.                 if len(start_list) >= stop_idx:
  881.                     return start_list[start_idx:stop_idx]
  882.  
  883.                 if stop == self._len:
  884.                     stop_pos = len(_lists) - 1
  885.                     stop_idx = len(_lists[stop_pos])
  886.                 else:
  887.                     stop_pos, stop_idx = self._pos(stop)
  888.  
  889.                 prefix = _lists[start_pos][start_idx:]
  890.                 middle = _lists[(start_pos + 1):stop_pos]
  891.                 result = reduce(iadd, middle, prefix)
  892.                 result += _lists[stop_pos][:stop_idx]
  893.  
  894.                 return result
  895.  
  896.             if step == -1 and start > stop:
  897.                 result = self._getitem(slice(stop + 1, start + 1))
  898.                 result.reverse()
  899.                 return result
  900.  
  901.             # Return a list because a negative step could
  902.             # reverse the order of the items and this could
  903.             # be the desired behavior.
  904.  
  905.             indices = range(start, stop, step)
  906.             return list(self._getitem(index) for index in indices)
  907.         else:
  908.             if self._len:
  909.                 if index == 0:
  910.                     return _lists[0][0]
  911.                 elif index == -1:
  912.                     return _lists[-1][-1]
  913.             else:
  914.                 raise IndexError('list index out of range')
  915.  
  916.             if 0 <= index < len(_lists[0]):
  917.                 return _lists[0][index]
  918.  
  919.             len_last = len(_lists[-1])
  920.  
  921.             if -len_last < index < 0:
  922.                 return _lists[-1][len_last + index]
  923.  
  924.             pos, idx = self._pos(index)
  925.             return _lists[pos][idx]
  926.  
  927.     _getitem = __getitem__
  928.  
  929.  
  930.     def __setitem__(self, index, value):
  931.         """Raise not-implemented error.
  932.  
  933.        ``sl.__setitem__(index, value)`` <==> ``sl[index] = value``
  934.  
  935.        :raises NotImplementedError: use ``del sl[index]`` and
  936.            ``sl.add(value)`` instead
  937.  
  938.        """
  939.         message = 'use ``del sl[index]`` and ``sl.add(value)`` instead'
  940.         raise NotImplementedError(message)
  941.  
  942.  
  943.     def __iter__(self):
  944.         """Return an iterator over the sorted list.
  945.  
  946.        ``sl.__iter__()`` <==> ``iter(sl)``
  947.  
  948.        Iterating the sorted list while adding or deleting values may raise a
  949.        :exc:`RuntimeError` or fail to iterate over all values.
  950.  
  951.        """
  952.         return chain.from_iterable(self._lists)
  953.  
  954.  
  955.     def __reversed__(self):
  956.         """Return a reverse iterator over the sorted list.
  957.  
  958.        ``sl.__reversed__()`` <==> ``reversed(sl)``
  959.  
  960.        Iterating the sorted list while adding or deleting values may raise a
  961.        :exc:`RuntimeError` or fail to iterate over all values.
  962.  
  963.        """
  964.         return chain.from_iterable(map(reversed, reversed(self._lists)))
  965.  
  966.  
  967.     def reverse(self):
  968.         """Raise not-implemented error.
  969.  
  970.        Sorted list maintains values in ascending sort order. Values may not be
  971.        reversed in-place.
  972.  
  973.        Use ``reversed(sl)`` for an iterator over values in descending sort
  974.        order.
  975.  
  976.        Implemented to override `MutableSequence.reverse` which provides an
  977.        erroneous default implementation.
  978.  
  979.        :raises NotImplementedError: use ``reversed(sl)`` instead
  980.  
  981.        """
  982.         raise NotImplementedError('use ``reversed(sl)`` instead')
  983.  
  984.  
  985.     def islice(self, start=None, stop=None, reverse=False):
  986.         """Return an iterator that slices sorted list from `start` to `stop`.
  987.  
  988.        The `start` and `stop` index are treated inclusive and exclusive,
  989.        respectively.
  990.  
  991.        Both `start` and `stop` default to `None` which is automatically
  992.        inclusive of the beginning and end of the sorted list.
  993.  
  994.        When `reverse` is `True` the values are yielded from the iterator in
  995.        reverse order; `reverse` defaults to `False`.
  996.  
  997.        >>> sl = SortedList('abcdefghij')
  998.        >>> it = sl.islice(2, 6)
  999.        >>> list(it)
  1000.        ['c', 'd', 'e', 'f']
  1001.  
  1002.        :param int start: start index (inclusive)
  1003.        :param int stop: stop index (exclusive)
  1004.        :param bool reverse: yield values in reverse order
  1005.        :return: iterator
  1006.  
  1007.        """
  1008.         _len = self._len
  1009.  
  1010.         if not _len:
  1011.             return iter(())
  1012.  
  1013.         start, stop, _ = slice(start, stop).indices(self._len)
  1014.  
  1015.         if start >= stop:
  1016.             return iter(())
  1017.  
  1018.         _pos = self._pos
  1019.  
  1020.         min_pos, min_idx = _pos(start)
  1021.  
  1022.         if stop == _len:
  1023.             max_pos = len(self._lists) - 1
  1024.             max_idx = len(self._lists[-1])
  1025.         else:
  1026.             max_pos, max_idx = _pos(stop)
  1027.  
  1028.         return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
  1029.  
  1030.  
  1031.     def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse):
  1032.         """Return an iterator that slices sorted list using two index pairs.
  1033.  
  1034.        The index pairs are (min_pos, min_idx) and (max_pos, max_idx), the
  1035.        first inclusive and the latter exclusive. See `_pos` for details on how
  1036.        an index is converted to an index pair.
  1037.  
  1038.        When `reverse` is `True`, values are yielded from the iterator in
  1039.        reverse order.
  1040.  
  1041.        """
  1042.         _lists = self._lists
  1043.  
  1044.         if min_pos > max_pos:
  1045.             return iter(())
  1046.  
  1047.         if min_pos == max_pos:
  1048.             if reverse:
  1049.                 indices = reversed(range(min_idx, max_idx))
  1050.                 return map(_lists[min_pos].__getitem__, indices)
  1051.  
  1052.             indices = range(min_idx, max_idx)
  1053.             return map(_lists[min_pos].__getitem__, indices)
  1054.  
  1055.         next_pos = min_pos + 1
  1056.  
  1057.         if next_pos == max_pos:
  1058.             if reverse:
  1059.                 min_indices = range(min_idx, len(_lists[min_pos]))
  1060.                 max_indices = range(max_idx)
  1061.                 return chain(
  1062.                     map(_lists[max_pos].__getitem__, reversed(max_indices)),
  1063.                     map(_lists[min_pos].__getitem__, reversed(min_indices)),
  1064.                 )
  1065.  
  1066.             min_indices = range(min_idx, len(_lists[min_pos]))
  1067.             max_indices = range(max_idx)
  1068.             return chain(
  1069.                 map(_lists[min_pos].__getitem__, min_indices),
  1070.                 map(_lists[max_pos].__getitem__, max_indices),
  1071.             )
  1072.  
  1073.         if reverse:
  1074.             min_indices = range(min_idx, len(_lists[min_pos]))
  1075.             sublist_indices = range(next_pos, max_pos)
  1076.             sublists = map(_lists.__getitem__, reversed(sublist_indices))
  1077.             max_indices = range(max_idx)
  1078.             return chain(
  1079.                 map(_lists[max_pos].__getitem__, reversed(max_indices)),
  1080.                 chain.from_iterable(map(reversed, sublists)),
  1081.                 map(_lists[min_pos].__getitem__, reversed(min_indices)),
  1082.             )
  1083.  
  1084.         min_indices = range(min_idx, len(_lists[min_pos]))
  1085.         sublist_indices = range(next_pos, max_pos)
  1086.         sublists = map(_lists.__getitem__, sublist_indices)
  1087.         max_indices = range(max_idx)
  1088.         return chain(
  1089.             map(_lists[min_pos].__getitem__, min_indices),
  1090.             chain.from_iterable(sublists),
  1091.             map(_lists[max_pos].__getitem__, max_indices),
  1092.         )
  1093.  
  1094.  
  1095.     def irange(self, minimum=None, maximum=None, inclusive=(True, True),
  1096.                reverse=False):
  1097.         """Create an iterator of values between `minimum` and `maximum`.
  1098.  
  1099.        Both `minimum` and `maximum` default to `None` which is automatically
  1100.        inclusive of the beginning and end of the sorted list.
  1101.  
  1102.        The argument `inclusive` is a pair of booleans that indicates whether
  1103.        the minimum and maximum ought to be included in the range,
  1104.        respectively. The default is ``(True, True)`` such that the range is
  1105.        inclusive of both minimum and maximum.
  1106.  
  1107.        When `reverse` is `True` the values are yielded from the iterator in
  1108.        reverse order; `reverse` defaults to `False`.
  1109.  
  1110.        >>> sl = SortedList('abcdefghij')
  1111.        >>> it = sl.irange('c', 'f')
  1112.        >>> list(it)
  1113.        ['c', 'd', 'e', 'f']
  1114.  
  1115.        :param minimum: minimum value to start iterating
  1116.        :param maximum: maximum value to stop iterating
  1117.        :param inclusive: pair of booleans
  1118.        :param bool reverse: yield values in reverse order
  1119.        :return: iterator
  1120.  
  1121.        """
  1122.         _maxes = self._maxes
  1123.  
  1124.         if not _maxes:
  1125.             return iter(())
  1126.  
  1127.         _lists = self._lists
  1128.  
  1129.         # Calculate the minimum (pos, idx) pair. By default this location
  1130.         # will be inclusive in our calculation.
  1131.  
  1132.         if minimum is None:
  1133.             min_pos = 0
  1134.             min_idx = 0
  1135.         else:
  1136.             if inclusive[0]:
  1137.                 min_pos = bisect_left(_maxes, minimum)
  1138.  
  1139.                 if min_pos == len(_maxes):
  1140.                     return iter(())
  1141.  
  1142.                 min_idx = bisect_left(_lists[min_pos], minimum)
  1143.             else:
  1144.                 min_pos = bisect_right(_maxes, minimum)
  1145.  
  1146.                 if min_pos == len(_maxes):
  1147.                     return iter(())
  1148.  
  1149.                 min_idx = bisect_right(_lists[min_pos], minimum)
  1150.  
  1151.         # Calculate the maximum (pos, idx) pair. By default this location
  1152.         # will be exclusive in our calculation.
  1153.  
  1154.         if maximum is None:
  1155.             max_pos = len(_maxes) - 1
  1156.             max_idx = len(_lists[max_pos])
  1157.         else:
  1158.             if inclusive[1]:
  1159.                 max_pos = bisect_right(_maxes, maximum)
  1160.  
  1161.                 if max_pos == len(_maxes):
  1162.                     max_pos -= 1
  1163.                     max_idx = len(_lists[max_pos])
  1164.                 else:
  1165.                     max_idx = bisect_right(_lists[max_pos], maximum)
  1166.             else:
  1167.                 max_pos = bisect_left(_maxes, maximum)
  1168.  
  1169.                 if max_pos == len(_maxes):
  1170.                     max_pos -= 1
  1171.                     max_idx = len(_lists[max_pos])
  1172.                 else:
  1173.                     max_idx = bisect_left(_lists[max_pos], maximum)
  1174.  
  1175.         return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
  1176.  
  1177.  
  1178.     def __len__(self):
  1179.         """Return the size of the sorted list.
  1180.  
  1181.        ``sl.__len__()`` <==> ``len(sl)``
  1182.  
  1183.        :return: size of sorted list
  1184.  
  1185.        """
  1186.         return self._len
  1187.  
  1188.  
  1189.     def bisect_left(self, value):
  1190.         """Return an index to insert `value` in the sorted list.
  1191.  
  1192.        If the `value` is already present, the insertion point will be before
  1193.        (to the left of) any existing values.
  1194.  
  1195.        Similar to the `bisect` module in the standard library.
  1196.  
  1197.        Runtime complexity: `O(log(n))` -- approximate.
  1198.  
  1199.        >>> sl = SortedList([10, 11, 12, 13, 14])
  1200.        >>> sl.bisect_left(12)
  1201.        2
  1202.  
  1203.        :param value: insertion index of value in sorted list
  1204.        :return: index
  1205.  
  1206.        """
  1207.         _maxes = self._maxes
  1208.  
  1209.         if not _maxes:
  1210.             return 0
  1211.  
  1212.         pos = bisect_left(_maxes, value)
  1213.  
  1214.         if pos == len(_maxes):
  1215.             return self._len
  1216.  
  1217.         idx = bisect_left(self._lists[pos], value)
  1218.         return self._loc(pos, idx)
  1219.  
  1220.  
  1221.     def bisect_right(self, value):
  1222.         """Return an index to insert `value` in the sorted list.
  1223.  
  1224.        Similar to `bisect_left`, but if `value` is already present, the
  1225.        insertion point will be after (to the right of) any existing values.
  1226.  
  1227.        Similar to the `bisect` module in the standard library.
  1228.  
  1229.        Runtime complexity: `O(log(n))` -- approximate.
  1230.  
  1231.        >>> sl = SortedList([10, 11, 12, 13, 14])
  1232.        >>> sl.bisect_right(12)
  1233.        3
  1234.  
  1235.        :param value: insertion index of value in sorted list
  1236.        :return: index
  1237.  
  1238.        """
  1239.         _maxes = self._maxes
  1240.  
  1241.         if not _maxes:
  1242.             return 0
  1243.  
  1244.         pos = bisect_right(_maxes, value)
  1245.  
  1246.         if pos == len(_maxes):
  1247.             return self._len
  1248.  
  1249.         idx = bisect_right(self._lists[pos], value)
  1250.         return self._loc(pos, idx)
  1251.  
  1252.     bisect = bisect_right
  1253.     _bisect_right = bisect_right
  1254.  
  1255.  
  1256.     def count(self, value):
  1257.         """Return number of occurrences of `value` in the sorted list.
  1258.  
  1259.        Runtime complexity: `O(log(n))` -- approximate.
  1260.  
  1261.        >>> sl = SortedList([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])
  1262.        >>> sl.count(3)
  1263.        3
  1264.  
  1265.        :param value: value to count in sorted list
  1266.        :return: count
  1267.  
  1268.        """
  1269.         _maxes = self._maxes
  1270.  
  1271.         if not _maxes:
  1272.             return 0
  1273.  
  1274.         pos_left = bisect_left(_maxes, value)
  1275.  
  1276.         if pos_left == len(_maxes):
  1277.             return 0
  1278.  
  1279.         _lists = self._lists
  1280.         idx_left = bisect_left(_lists[pos_left], value)
  1281.         pos_right = bisect_right(_maxes, value)
  1282.  
  1283.         if pos_right == len(_maxes):
  1284.             return self._len - self._loc(pos_left, idx_left)
  1285.  
  1286.         idx_right = bisect_right(_lists[pos_right], value)
  1287.  
  1288.         if pos_left == pos_right:
  1289.             return idx_right - idx_left
  1290.  
  1291.         right = self._loc(pos_right, idx_right)
  1292.         left = self._loc(pos_left, idx_left)
  1293.         return right - left
  1294.  
  1295.  
  1296.     def copy(self):
  1297.         """Return a shallow copy of the sorted list.
  1298.  
  1299.        Runtime complexity: `O(n)`
  1300.  
  1301.        :return: new sorted list
  1302.  
  1303.        """
  1304.         return self.__class__(self)
  1305.  
  1306.     __copy__ = copy
  1307.  
  1308.  
  1309.     def append(self, value):
  1310.         """Raise not-implemented error.
  1311.  
  1312.        Implemented to override `MutableSequence.append` which provides an
  1313.        erroneous default implementation.
  1314.  
  1315.        :raises NotImplementedError: use ``sl.add(value)`` instead
  1316.  
  1317.        """
  1318.         raise NotImplementedError('use ``sl.add(value)`` instead')
  1319.  
  1320.  
  1321.     def extend(self, values):
  1322.         """Raise not-implemented error.
  1323.  
  1324.        Implemented to override `MutableSequence.extend` which provides an
  1325.        erroneous default implementation.
  1326.  
  1327.        :raises NotImplementedError: use ``sl.update(values)`` instead
  1328.  
  1329.        """
  1330.         raise NotImplementedError('use ``sl.update(values)`` instead')
  1331.  
  1332.  
  1333.     def insert(self, index, value):
  1334.         """Raise not-implemented error.
  1335.  
  1336.        :raises NotImplementedError: use ``sl.add(value)`` instead
  1337.  
  1338.        """
  1339.         raise NotImplementedError('use ``sl.add(value)`` instead')
  1340.  
  1341.  
  1342.     def pop(self, index=-1):
  1343.         """Remove and return value at `index` in sorted list.
  1344.  
  1345.        Raise :exc:`IndexError` if the sorted list is empty or index is out of
  1346.        range.
  1347.  
  1348.        Negative indices are supported.
  1349.  
  1350.        Runtime complexity: `O(log(n))` -- approximate.
  1351.  
  1352.        >>> sl = SortedList('abcde')
  1353.        >>> sl.pop()
  1354.        'e'
  1355.        >>> sl.pop(2)
  1356.        'c'
  1357.        >>> sl
  1358.        SortedList(['a', 'b', 'd'])
  1359.  
  1360.        :param int index: index of value (default -1)
  1361.        :return: value
  1362.        :raises IndexError: if index is out of range
  1363.  
  1364.        """
  1365.         if not self._len:
  1366.             raise IndexError('pop index out of range')
  1367.  
  1368.         _lists = self._lists
  1369.  
  1370.         if index == 0:
  1371.             val = _lists[0][0]
  1372.             self._delete(0, 0)
  1373.             return val
  1374.  
  1375.         if index == -1:
  1376.             pos = len(_lists) - 1
  1377.             loc = len(_lists[pos]) - 1
  1378.             val = _lists[pos][loc]
  1379.             self._delete(pos, loc)
  1380.             return val
  1381.  
  1382.         if 0 <= index < len(_lists[0]):
  1383.             val = _lists[0][index]
  1384.             self._delete(0, index)
  1385.             return val
  1386.  
  1387.         len_last = len(_lists[-1])
  1388.  
  1389.         if -len_last < index < 0:
  1390.             pos = len(_lists) - 1
  1391.             loc = len_last + index
  1392.             val = _lists[pos][loc]
  1393.             self._delete(pos, loc)
  1394.             return val
  1395.  
  1396.         pos, idx = self._pos(index)
  1397.         val = _lists[pos][idx]
  1398.         self._delete(pos, idx)
  1399.         return val
  1400.  
  1401.  
  1402.     def index(self, value, start=None, stop=None):
  1403.         """Return first index of value in sorted list.
  1404.  
  1405.        Raise ValueError if `value` is not present.
  1406.  
  1407.        Index must be between `start` and `stop` for the `value` to be
  1408.        considered present. The default value, None, for `start` and `stop`
  1409.        indicate the beginning and end of the sorted list.
  1410.  
  1411.        Negative indices are supported.
  1412.  
  1413.        Runtime complexity: `O(log(n))` -- approximate.
  1414.  
  1415.        >>> sl = SortedList('abcde')
  1416.        >>> sl.index('d')
  1417.        3
  1418.        >>> sl.index('z')
  1419.        Traceback (most recent call last):
  1420.          ...
  1421.        ValueError: 'z' is not in list
  1422.  
  1423.        :param value: value in sorted list
  1424.        :param int start: start index (default None, start of sorted list)
  1425.        :param int stop: stop index (default None, end of sorted list)
  1426.        :return: index of value
  1427.        :raises ValueError: if value is not present
  1428.  
  1429.        """
  1430.         _len = self._len
  1431.  
  1432.         if not _len:
  1433.             raise ValueError('{0!r} is not in list'.format(value))
  1434.  
  1435.         if start is None:
  1436.             start = 0
  1437.         if start < 0:
  1438.             start += _len
  1439.         if start < 0:
  1440.             start = 0
  1441.  
  1442.         if stop is None:
  1443.             stop = _len
  1444.         if stop < 0:
  1445.             stop += _len
  1446.         if stop > _len:
  1447.             stop = _len
  1448.  
  1449.         if stop <= start:
  1450.             raise ValueError('{0!r} is not in list'.format(value))
  1451.  
  1452.         _maxes = self._maxes
  1453.         pos_left = bisect_left(_maxes, value)
  1454.  
  1455.         if pos_left == len(_maxes):
  1456.             raise ValueError('{0!r} is not in list'.format(value))
  1457.  
  1458.         _lists = self._lists
  1459.         idx_left = bisect_left(_lists[pos_left], value)
  1460.  
  1461.         if _lists[pos_left][idx_left] != value:
  1462.             raise ValueError('{0!r} is not in list'.format(value))
  1463.  
  1464.         stop -= 1
  1465.         left = self._loc(pos_left, idx_left)
  1466.  
  1467.         if start <= left:
  1468.             if left <= stop:
  1469.                 return left
  1470.         else:
  1471.             right = self._bisect_right(value) - 1
  1472.  
  1473.             if start <= right:
  1474.                 return start
  1475.  
  1476.         raise ValueError('{0!r} is not in list'.format(value))
  1477.  
  1478.  
  1479.     def __add__(self, other):
  1480.         """Return new sorted list containing all values in both sequences.
  1481.  
  1482.        ``sl.__add__(other)`` <==> ``sl + other``
  1483.  
  1484.        Values in `other` do not need to be in sorted order.
  1485.  
  1486.        Runtime complexity: `O(n*log(n))`
  1487.  
  1488.        >>> sl1 = SortedList('bat')
  1489.        >>> sl2 = SortedList('cat')
  1490.        >>> sl1 + sl2
  1491.        SortedList(['a', 'a', 'b', 'c', 't', 't'])
  1492.  
  1493.        :param other: other iterable
  1494.        :return: new sorted list
  1495.  
  1496.        """
  1497.         values = reduce(iadd, self._lists, [])
  1498.         values.extend(other)
  1499.         return self.__class__(values)
  1500.  
  1501.     __radd__ = __add__
  1502.  
  1503.  
  1504.     def __iadd__(self, other):
  1505.         """Update sorted list with values from `other`.
  1506.  
  1507.        ``sl.__iadd__(other)`` <==> ``sl += other``
  1508.  
  1509.        Values in `other` do not need to be in sorted order.
  1510.  
  1511.        Runtime complexity: `O(k*log(n))` -- approximate.
  1512.  
  1513.        >>> sl = SortedList('bat')
  1514.        >>> sl += 'cat'
  1515.        >>> sl
  1516.        SortedList(['a', 'a', 'b', 'c', 't', 't'])
  1517.  
  1518.        :param other: other iterable
  1519.        :return: existing sorted list
  1520.  
  1521.        """
  1522.         self._update(other)
  1523.         return self
  1524.  
  1525.  
  1526.     def __mul__(self, num):
  1527.         """Return new sorted list with `num` shallow copies of values.
  1528.  
  1529.        ``sl.__mul__(num)`` <==> ``sl * num``
  1530.  
  1531.        Runtime complexity: `O(n*log(n))`
  1532.  
  1533.        >>> sl = SortedList('abc')
  1534.        >>> sl * 3
  1535.        SortedList(['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'])
  1536.  
  1537.        :param int num: count of shallow copies
  1538.        :return: new sorted list
  1539.  
  1540.        """
  1541.         values = reduce(iadd, self._lists, []) * num
  1542.         return self.__class__(values)
  1543.  
  1544.     __rmul__ = __mul__
  1545.  
  1546.  
  1547.     def __imul__(self, num):
  1548.         """Update the sorted list with `num` shallow copies of values.
  1549.  
  1550.        ``sl.__imul__(num)`` <==> ``sl *= num``
  1551.  
  1552.        Runtime complexity: `O(n*log(n))`
  1553.  
  1554.        >>> sl = SortedList('abc')
  1555.        >>> sl *= 3
  1556.        >>> sl
  1557.        SortedList(['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'])
  1558.  
  1559.        :param int num: count of shallow copies
  1560.        :return: existing sorted list
  1561.  
  1562.        """
  1563.         values = reduce(iadd, self._lists, []) * num
  1564.         self._clear()
  1565.         self._update(values)
  1566.         return self
  1567.  
  1568.  
  1569.     def __make_cmp(seq_op, symbol, doc):
  1570.         "Make comparator method."
  1571.         def comparer(self, other):
  1572.             "Compare method for sorted list and sequence."
  1573.             if not isinstance(other, Sequence):
  1574.                 return NotImplemented
  1575.  
  1576.             self_len = self._len
  1577.             len_other = len(other)
  1578.  
  1579.             if self_len != len_other:
  1580.                 if seq_op is eq:
  1581.                     return False
  1582.                 if seq_op is ne:
  1583.                     return True
  1584.  
  1585.             for alpha, beta in zip(self, other):
  1586.                 if alpha != beta:
  1587.                     return seq_op(alpha, beta)
  1588.  
  1589.             return seq_op(self_len, len_other)
  1590.  
  1591.         seq_op_name = seq_op.__name__
  1592.         comparer.__name__ = '__{0}__'.format(seq_op_name)
  1593.         doc_str = """Return true if and only if sorted list is {0} `other`.
  1594.  
  1595.        ``sl.__{1}__(other)`` <==> ``sl {2} other``
  1596.  
  1597.        Comparisons use lexicographical order as with sequences.
  1598.  
  1599.        Runtime complexity: `O(n)`
  1600.  
  1601.        :param other: `other` sequence
  1602.        :return: true if sorted list is {0} `other`
  1603.  
  1604.        """
  1605.         comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))
  1606.         return comparer
  1607.  
  1608.  
  1609.     __eq__ = __make_cmp(eq, '==', 'equal to')
  1610.     __ne__ = __make_cmp(ne, '!=', 'not equal to')
  1611.     __lt__ = __make_cmp(lt, '<', 'less than')
  1612.     __gt__ = __make_cmp(gt, '>', 'greater than')
  1613.     __le__ = __make_cmp(le, '<=', 'less than or equal to')
  1614.     __ge__ = __make_cmp(ge, '>=', 'greater than or equal to')
  1615.     __make_cmp = staticmethod(__make_cmp)
  1616.  
  1617.  
  1618.     def __reduce__(self):
  1619.         values = reduce(iadd, self._lists, [])
  1620.         return (type(self), (values,))
  1621.  
  1622.  
  1623.     @recursive_repr()
  1624.     def __repr__(self):
  1625.         """Return string representation of sorted list.
  1626.  
  1627.        ``sl.__repr__()`` <==> ``repr(sl)``
  1628.  
  1629.        :return: string representation
  1630.  
  1631.        """
  1632.         return '{0}({1!r})'.format(type(self).__name__, list(self))
  1633.  
  1634.  
  1635.     def _check(self):
  1636.         """Check invariants of sorted list.
  1637.  
  1638.        Runtime complexity: `O(n)`
  1639.  
  1640.        """
  1641.         try:
  1642.             assert self._load >= 4
  1643.             assert len(self._maxes) == len(self._lists)
  1644.             assert self._len == sum(len(sublist) for sublist in self._lists)
  1645.  
  1646.             # Check all sublists are sorted.
  1647.  
  1648.             for sublist in self._lists:
  1649.                 for pos in range(1, len(sublist)):
  1650.                     assert sublist[pos - 1] <= sublist[pos]
  1651.  
  1652.             # Check beginning/end of sublists are sorted.
  1653.  
  1654.             for pos in range(1, len(self._lists)):
  1655.                 assert self._lists[pos - 1][-1] <= self._lists[pos][0]
  1656.  
  1657.             # Check _maxes index is the last value of each sublist.
  1658.  
  1659.             for pos in range(len(self._maxes)):
  1660.                 assert self._maxes[pos] == self._lists[pos][-1]
  1661.  
  1662.             # Check sublist lengths are less than double load-factor.
  1663.  
  1664.             double = self._load << 1
  1665.             assert all(len(sublist) <= double for sublist in self._lists)
  1666.  
  1667.             # Check sublist lengths are greater than half load-factor for all
  1668.             # but the last sublist.
  1669.  
  1670.             half = self._load >> 1
  1671.             for pos in range(0, len(self._lists) - 1):
  1672.                 assert len(self._lists[pos]) >= half
  1673.  
  1674.             if self._index:
  1675.                 assert self._len == self._index[0]
  1676.                 assert len(self._index) == self._offset + len(self._lists)
  1677.  
  1678.                 # Check index leaf nodes equal length of sublists.
  1679.  
  1680.                 for pos in range(len(self._lists)):
  1681.                     leaf = self._index[self._offset + pos]
  1682.                     assert leaf == len(self._lists[pos])
  1683.  
  1684.                 # Check index branch nodes are the sum of their children.
  1685.  
  1686.                 for pos in range(self._offset):
  1687.                     child = (pos << 1) + 1
  1688.                     if child >= len(self._index):
  1689.                         assert self._index[pos] == 0
  1690.                     elif child + 1 == len(self._index):
  1691.                         assert self._index[pos] == self._index[child]
  1692.                     else:
  1693.                         child_sum = self._index[child] + self._index[child + 1]
  1694.                         assert child_sum == self._index[pos]
  1695.         except:
  1696.             traceback.print_exc(file=sys.stdout)
  1697.             print('len', self._len)
  1698.             print('load', self._load)
  1699.             print('offset', self._offset)
  1700.             print('len_index', len(self._index))
  1701.             print('index', self._index)
  1702.             print('len_maxes', len(self._maxes))
  1703.             print('maxes', self._maxes)
  1704.             print('len_lists', len(self._lists))
  1705.             print('lists', self._lists)
  1706.             raise
  1707.  
  1708.  
  1709.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement