### Install Sorted Containers from Source Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Install Sorted Containers into your Python environment after cloning the source repository. ```bash python3 -m pip install . ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/development.md Install all necessary packages for building, testing, and running benchmarks using pip. Ensure you have a requirements.txt file in your project directory. ```bash $ pip install -r requirements.txt ``` -------------------------------- ### Clone the Sorted Containers Repository Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/development.md Use this command to get a local copy of the source code from GitHub. This is the recommended way to start development. ```bash $ git clone git://github.com/grantjenks/python-sortedcontainers.git ``` -------------------------------- ### SortedSet Example Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/README.rst Shows how to create and use a SortedSet, which stores unique elements in sorted order. This example demonstrates initialization from an iterable and using `bisect_left` for efficient searching. ```python >>> from sortedcontainers import SortedSet >>> ss = SortedSet('abracadabra') >>> ss SortedSet(['a', 'b', 'c', 'd', 'r']) >>> ss.bisect_left('c') 2 ``` -------------------------------- ### Creating Record Instances Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Creates instances of the 'Record' data type for use in examples. ```python >>> alice1 = Record('alice', 1) >>> bob2 = Record('bob', 2) >>> carol3 = Record('carol', 3) ``` -------------------------------- ### Install Sorted Containers Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/index.md Install the sortedcontainers library using pip. This is the standard method for adding Python packages to your project. ```default $ pip install sortedcontainers ``` -------------------------------- ### SortedList Example Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/README.rst Demonstrates the creation and basic operations of a SortedList, including initialization, multiplication for size, counting elements, and slicing. This is useful for maintaining ordered lists with efficient element access and modification. ```python >>> from sortedcontainers import SortedList >>> sl = SortedList(['e', 'a', 'c', 'd', 'b']) >>> sl SortedList(['a', 'b', 'c', 'd', 'e']) >>> sl *= 10_000_000 >>> sl.count('c') 10000000 >>> sl[-3:] ['e', 'e', 'e'] ``` -------------------------------- ### Install Sorted Containers with Pipenv Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Use this command to install Sorted Containers if you are managing your project dependencies with Pipenv. ```bash pipenv install sortedcontainers ``` -------------------------------- ### Install Sorted Containers with Pip Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Use this command to install the latest version of Sorted Containers from the Python Package Index. ```bash python3 -m pip install sortedcontainers ``` -------------------------------- ### SortedDict Example Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/README.rst Illustrates the usage of SortedDict for ordered key-value pairs. It shows initialization, and the `popitem` method for removing and returning the last item, useful for ordered dictionary operations. ```python >>> from sortedcontainers import SortedDict >>> sd = SortedDict({'c': -3, 'a': 1, 'b': 2}) >>> sd SortedDict({'a': 1, 'b': 2, 'c': -3}) >>> sd.popitem(index=-1) ('c', -3) ``` -------------------------------- ### SortedList Index Tree Traversal Example Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/implementation.md Demonstrates the traversal logic for indexing into the SortedList's internal index tree. It shows how to navigate the tree to find the correct sublist and position. ```default _index = 14 5 9 3 2 4 5 _offset = 3 Tree: 14 5 9 3 2 4 5 ``` -------------------------------- ### SortedList Internal Structure Example Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/implementation.md Illustrates the structure of the internal index used by SortedList, which is a dense binary tree of pairwise sums of sublist lengths. ```default list(map(len, _lists)) -> [3, 5, 4, 5, 6] ``` ```default [8, 9, 6, 0] ``` ```default [17, 6] ``` ```default [23, 17, 6, 8, 9, 6, 0, 3, 5, 4, 5, 6] ``` -------------------------------- ### SortedDict Key Lookup Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Shows how to look up keys in a SortedDict using mapping interface methods like `__getitem__`, `__contains__`, `get`, and `peekitem`. ```APIDOC ## SortedDict Key Lookup ### Description Perform key lookups in a `SortedDict` using mapping interface methods such as `__getitem__`, `__contains__`, `get`, and `peekitem`. ### Method `__getitem__`, `__contains__`, `get`, `peekitem` ### Endpoint N/A (Python class methods) ### Request Example ```python from sortedcontainers import SortedDict sd = SortedDict({'a': 1, 'b': 2}) value_b = sd['b'] contains_c = 'c' in sd value_z = sd.get('z') last_item = sd.peekitem(index=-1) print(f"Value of 'b': {value_b}") print(f"Contains 'c': {contains_c}") print(f"Value of 'z': {value_z}") print(f"Last item: {last_item}") ``` ### Response Example ``` Value of 'b': 2 Contains 'c': False Value of 'z': None Last item: ('b', 2) ``` ``` -------------------------------- ### Run Tests with setup.py Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/development.md Execute tests using the setup.py script. This command downloads a minimal testing infrastructure and runs the tests. ```bash $ python setup.py test ``` -------------------------------- ### Run All Benchmarks Locally Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/development.md Download the project, set up the Python path, and run benchmarks for SortedList, SortedDict, and SortedSet locally. ```bash $ curl -OL https://github.com/grantjenks/python-sortedcontainers/zipball/master $ unzip master $ cd grantjenks-python-sortedcontainers-[GITHASH]/ $ export PYTHONPATH=`pwd` $ python -m tests.benchmark_sortedlist $ python -m tests.benchmark_sorteddict $ python -m tests.benchmark_sortedset ``` -------------------------------- ### Setup.py Test Execution Output Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/development.md This output shows the detailed steps and results when running tests via `python setup.py test`, including package information, build processes, and test session summaries. ```text running test running egg_info writing sortedcontainers.egg-info/PKG-INFO writing dependency_links to sortedcontainers.egg-info/dependency_links.txt writing top-level names to sortedcontainers.egg-info/top_level.txt reading manifest file 'sortedcontainers.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' writing manifest file 'sortedcontainers.egg-info/SOURCES.txt' running build_ext G LOB sdist-make: /Users/grantj/repos/python-sortedcontainers/setup.py py36 inst-nodeps: /Users/grantj/repos/python-sortedcontainers/.tox/dist/sortedcontainers-1.5.10.zip py36 installed: attrs==18.1.0,more-itertools==4.1.0,pluggy==0.6.0,py==1.5.3,pytest==3.5.1,six==1.11.0,sortedcontainers==1.5.10 py36 runtests: PYTHONHASHSEED='365015869' py36 runtests: commands[0] | python -m pytest ================================================= test session starts ================================================= platform darwin -- Python 3.6.5, pytest-3.5.1, py-1.5.3, pluggy-0.6.0 rootdir: /Users/grantj/repos/python-sortedcontainers, inifile: tox.ini collected 357 items docs/introduction.rst . [ 0%] sortedcontainers/__init__.py . [ 0%] sortedcontainers/sorteddict.py ........... [ 3%] sortedcontainers/sortedlist.py ..................................... [ 14%] sortedcontainers/sortedset.py ................. [ 18%] tests/benchmark_splits_fill.py . [ 19%] tests/sortedcollection.py . [ 19%] tests/test_coverage_sorteddict.py ................................................... [ 33%] tests/test_coverage_sortedkeylist_modulo.py ................................................................... [ 52%] tests/test_coverage_sortedkeylist_negate.py ....................................................... [ 68%] tests/test_coverage_sortedlist.py .......................................................... [ 84%] tests/test_coverage_sortedset.py .................................................. [ 98%] tests/test_stress_sorteddict.py .. [ 98%] tests/test_stress_sortedkeylist.py . [ 99%] tests/test_stress_sortedlist.py . [ 99%] tests/test_stress_sortedset.py .. [100%] ============================================= 357 passed in 10.86 seconds ============================================= lint inst-nodeps: /Users/grantj/repos/python-sortedcontainers/.tox/dist/sortedcontainers-1.5.10.zip lint installed: astroid==1.6.4,isort==4.3.4,lazy-object-proxy==1.3.1,mccabe==0.6.1,pylint==1.9.0,six==1.11.0,sortedcontainers==1.5.10,wrapt==1.10.11 lint runtests: PYTHONHASHSEED='365015869' lint runtests: commands[0] | pylint sortedcontainers Using config file /Users/grantj/repos/python-sortedcontainers/.pylintrc -------------------------------------------------------------------- Your code has been rated at 10.00/10 (previous run: 10.00/10, +0.00) _______________________________________________________ summary _______________________________________________________ py36: commands succeeded lint: commands succeeded ``` -------------------------------- ### Initialize SortedList Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Import and create an empty SortedList instance. ```python from sortedcontainers import SortedList sl = SortedList() ``` -------------------------------- ### SortedDict Initialization and Item Addition Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Demonstrates how to initialize a SortedDict and add items using various methods. Keys are automatically kept in sorted order. ```APIDOC ## SortedDict Initialization and Item Addition ### Description Initialize a `SortedDict` and add items using `__setitem__`, `update`, or `setdefault`. The keys will remain sorted. ### Method `__setitem__`, `update`, `setdefault` ### Endpoint N/A (Python class methods) ### Request Example ```python from sortedcontainers import SortedDict sd = SortedDict() sd['e'] = 5 sd['b'] = 2 sd.update({'d': 4, 'c': 3}) sd.setdefault('a', 1) print(sd) ``` ### Response Example ``` SortedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}) ``` ``` -------------------------------- ### Run and Plot SortedList Benchmarks Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/development.md Execute benchmarks for SortedList, plot the results, and save the graphs. Use --help for script arguments. ```bash $ python -m tests.benchmark_sortedlist --bare > tests/results_sortedlist.txt $ python -m tests.benchmark_plot tests/results_sortedlist.txt SortedList --save ``` -------------------------------- ### Lookup Items in SortedDict Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Supports standard mapping lookups like __getitem__, __contains__, and get. peekitem allows looking up the item at a specific index without removing it. ```python >>> sd['b'] 2 >>> 'c' in sd False >>> sd.get('z') is None True >>> sd.peekitem(index=-1) ('b', 2) ``` -------------------------------- ### Initialize SortedSet Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Import and initialize an empty SortedSet. Values must be hashable and comparable. ```python >>> from sortedcontainers import SortedSet >>> ss = SortedSet() ``` -------------------------------- ### Initialize SortedKeyList with a Key Function Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Initialize a SortedKeyList with a key function to define the ordering of elements. The key function extracts a comparison key for ordering. ```python >>> from operator import neg >>> from sortedcontainers import SortedKeyList >>> skl = SortedKeyList(key=neg) ``` -------------------------------- ### Initialize SortedDict Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Create an empty SortedDict instance. Keys must be hashable and comparable, and their hash and total ordering must not change while stored. ```python >>> from sortedcontainers import SortedDict >>> sd = SortedDict() ``` -------------------------------- ### SortedDict Initialization with Key Function Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Demonstrates initializing a SortedDict with a custom key function to alter the sorting order of keys. ```APIDOC ## SortedDict Initialization with Key Function ### Description Initialize a `SortedDict` with an optional key function as the first positional argument. This function extracts a comparison key from the dictionary keys, allowing for custom sorting orders. ### Method `SortedDict()` constructor with positional argument ### Endpoint N/A (Python class constructor) ### Request Example ```python import operator from sortedcontainers import SortedDict # Example: Initialize with integer keys in descending order using a negating key function def neg(x): return -x sd = SortedDict(neg, enumerate('abc', start=1)) print(sd) keys = sd.keys() print(list(keys)) ``` ### Response Example ``` SortedDict({3: 'c', 2: 'b', 1: 'a'}) [3, 2, 1] ``` ``` -------------------------------- ### SortedList, SortedDict, and SortedSet Usage Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/index.md Demonstrates the creation and basic operations of SortedList, SortedDict, and SortedSet. SortedList supports efficient sorting and manipulation, SortedDict maintains key-value pairs in sorted order, and SortedSet stores unique elements in sorted order. All operations are faster than linear time. ```python >>> from sortedcontainers import SortedList >>> sl = SortedList(['e', 'a', 'c', 'd', 'b']) >>> sl SortedList(['a', 'b', 'c', 'd', 'e']) >>> sl *= 10_000_000 >>> sl.count('c') 10000000 >>> sl[-3:] ['e', 'e', 'e'] ``` ```python >>> from sortedcontainers import SortedDict >>> sd = SortedDict({'c': -3, 'a': 1, 'b': 2}) >>> sd SortedDict({'a': 1, 'b': 2, 'c': -3}) >>> sd.popitem(index=-1) ('c', -3) ``` ```python >>> from sortedcontainers import SortedSet >>> ss = SortedSet('abracadabra') >>> ss SortedSet(['a', 'b', 'c', 'd', 'r']) >>> ss.bisect_left('c') 2 ``` -------------------------------- ### Using Record Instances in SortedList Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Demonstrates that distinct instances of Record with different ranks are correctly handled in SortedList, highlighting the importance of instance identity for equality. ```python >>> alice1 = Record('alice', 1) >>> bob2 = Record('bob', 2) >>> carol3 = Record('carol', 3) >>> bob4 = Record('bob', 4) >>> bob2 != bob4 # <-- Different instances, so unequal. GOOD! True >>> sl = SortedList([alice1, bob2, carol3, bob4]) >>> bob2 in sl True >>> bob4 in sl True ``` -------------------------------- ### Initialize SortedSet with a Key Function Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Shows how to initialize a SortedSet with a custom key function. The key function is used to extract a comparison key from each element, allowing for custom sorting logic. ```python >>> ss = SortedSet([1, 2, 3], key=neg) >>> ss SortedSet([3, 2, 1], key=) ``` -------------------------------- ### Initialize SortedDict with Key Function Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md The initializer accepts an optional key-function to transform keys for comparison, enabling custom sorting orders like descending integers. ```python >>> def neg(x): ... return -x >>> sd = SortedDict(neg, enumerate('abc', start=1)) >>> sd SortedDict(, {3: 'c', 2: 'b', 1: 'a'}) >>> keys = sd.keys() >>> list(keys) [3, 2, 1] ``` -------------------------------- ### Access Help in Python Interpreter Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/index.md Use Python's built-in help() function to access documentation for the sortedcontainers module, specific classes like SortedDict, and their methods. ```python >>> import sortedcontainers >>> help(sortedcontainers) >>> from sortedcontainers import SortedDict >>> help(SortedDict) >>> help(SortedDict.popitem) ``` -------------------------------- ### SortedList Methods on SortedSet Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Demonstrates the use of SortedList methods such as bisect, index, irange, and islice on a SortedSet. These methods leverage the sorted nature of the set for efficient lookups and range queries. ```python >>> ss = SortedSet('abcdef') >>> ss.bisect('d') 4 >>> ss.index('f') 5 >>> list(ss.irange('b', 'e')) ['b', 'c', 'd', 'e'] >>> list(ss.islice(-3)) ['d', 'e', 'f'] ``` -------------------------------- ### Access Elements and Reverse SortedSet Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Shows how to access elements by index and iterate through the set in reverse order. Also demonstrates deleting elements by index and popping the last element. ```python >>> ss[0] 'c' >>> list(reversed(ss)) ['f', 'e', 'd', 'c'] >>> del ss[0] >>> ss.pop(index=-1) 'f' >>> ss SortedSet(['d', 'e']) ``` -------------------------------- ### Run Stress Tests for SortedList Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/development.md Execute stress tests for the SortedList data type. This command takes an iteration count and a random seed as arguments. It's useful for rigorous testing with a high number of operations. ```bash $ python -m tests.test_stress_sortedlist 1000 0 ``` -------------------------------- ### Default Object Equality in Python Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Illustrates the default equality implementation for Python objects, which is based on identity. Instances of 'object' cannot be stored in a SortedList because they lack comparison methods. ```python >>> class Object: ... def __eq__(self, other): ... return id(self) == id(other) ``` -------------------------------- ### Using SortedKeyList Key-Based Methods Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md SortedKeyList extends SortedList with methods that operate on keys rather than values. These include bisect_key_left, bisect_key_right, and irange_key for efficient searching and iteration based on the key function. ```python >>> skl = SortedKeyList([1, 2, 3, 4, 5], key=neg) >>> skl SortedKeyList([5, 4, 3, 2, 1], key=) >>> skl.bisect_key_left(-4.5) 1 >>> skl.bisect_key_right(-1.5) 4 >>> list(skl.irange_key(-4.5, -1.5)) [4, 3, 2] ``` -------------------------------- ### Add, Discard, Remove, and Update Elements in SortedSet Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Demonstrates adding elements, checking for membership, discarding elements that may not exist, removing elements that must exist, and updating the set with multiple elements. The SortedSet maintains elements in sorted order. ```python >>> ss.add('c') >>> ss.add('a') >>> ss.add('b') >>> ss SortedSet(['a', 'b', 'c']) >>> 'c' in ss True >>> ss.discard('a') >>> ss.remove('b') >>> _ = ss.update('def') >>> ss SortedSet(['c', 'd', 'e', 'f']) ``` -------------------------------- ### SortedDict Sequence Lookup Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Demonstrates sequence-based lookups in a SortedDict using methods like `bisect_right`, `index`, and `irange`. ```APIDOC ## SortedDict Sequence Lookup ### Description Utilize sequence interface methods for lookups in a `SortedDict`, including `bisect_right`, `index`, and `irange`. ### Method `bisect_right`, `index`, `irange` ### Endpoint N/A (Python class methods) ### Request Example ```python from sortedcontainers import SortedDict sd = SortedDict({'a': 1, 'b': 2, 'c': 3}) index_of_b = sd.index('b') range_a_to_z = list(sd.irange('a', 'z')) print(f"Index of 'b': {index_of_b}") print(f"Items in range 'a' to 'z': {range_a_to_z}") ``` ### Response Example ``` Index of 'b': 1 Items in range 'a' to 'z': ['a', 'b', 'c'] ``` ``` -------------------------------- ### SortedDict Views Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Keys, items, and values views support both set and sequence semantics, with optimized methods for index-based lookups. ```python >>> keys = sd.keys() >>> keys[0] 'a' >>> items = sd.items() >>> items[-1] ('b', 2) >>> values = sd.values() >>> values[:] [1, 2] ``` -------------------------------- ### Sequence Lookups in SortedDict Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md The sequence interface provides methods like bisect_right and index for efficient lookups based on sorted order. ```python >>> sd.bisect_right('b') 2 >>> sd.index('a') 0 >>> list(sd.irange('a', 'z')) ['a', 'b'] ``` -------------------------------- ### Construct SortedList with a Key Function Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md A SortedKeyList can be constructed using the SortedList type by passing a key-function to the initializer. This demonstrates that SortedKeyList is a subclass of SortedList and retains the key function. ```python >>> from sortedcontainers import SortedList >>> values = SortedList([1, 2, 3, 4, 5], key=neg) >>> values SortedKeyList([5, 4, 3, 2, 1], key=) >>> isinstance(values, SortedList) True >>> issubclass(SortedKeyList, SortedList) True >>> values.key ``` -------------------------------- ### SortedDict with Custom __missing__ Method Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Shows how to create a `DefaultSortedDict` subclass that mimics `collections.defaultdict` by providing a default value for missing keys. ```APIDOC ## SortedDict with Custom __missing__ Method ### Description Subclass `SortedDict` to implement a `__missing__` method, similar to `collections.defaultdict`. This allows for automatic creation of missing keys with a default value. ### Method `__missing__` method override ### Endpoint N/A (Python class method) ### Request Example ```python from sortedcontainers import SortedDict class DefaultSortedDict(SortedDict): def __missing__(self, key): value = 0 self[key] = value return value dsd = DefaultSortedDict() missing_value = dsd['z'] print(f"Value for missing key 'z': {missing_value}") print(dsd) ``` ### Response Example ``` Value for missing key 'z': 0 SortedDict({'z': 0}) ``` ``` -------------------------------- ### Define Record Comparison with _cmp_key Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Use a comparison-key method like _cmp_key to define equality and ordering based on specific fields. This ensures consistent sorting when custom objects are stored in SortedList. ```python >>> class Record(object): ... def __init__(self, name, rank): ... self.name = name ... self.rank = rank ... def _cmp_key(self): ... return (self.rank, self.name) ... def __eq__(self, other): ... return self._cmp_key() == other._cmp_key() ... def __lt__(self, other): ... return self._cmp_key() < other._cmp_key() ``` -------------------------------- ### Set Operations on SortedSet Source: https://github.com/grantjenks/python-sortedcontainers/blob/master/docs/introduction.md Illustrates common set operations like difference, intersection, symmetric difference, and union, including their in-place variants and operator equivalents. SortedSets support these operations efficiently. ```python >>> abcd = SortedSet('abcd') >>> cdef = SortedSet('cdef') >>> abcd.difference(cdef) SortedSet(['a', 'b']) >>> abcd.intersection(cdef) SortedSet(['c', 'd']) >>> abcd.symmetric_difference(cdef) SortedSet(['a', 'b', 'e', 'f']) >>> abcd.union(cdef) SortedSet(['a', 'b', 'c', 'd', 'e', 'f']) >>> abcd | cdef SortedSet(['a', 'b', 'c', 'd', 'e', 'f']) >>> abcd |= cdef >>> abcd SortedSet(['a', 'b', 'c', 'd', 'e', 'f']) ```