MCPcopy Create free account
hub / github.com/grantjenks/python-sortedcontainers / SortedCollection

Class SortedCollection

tests/sortedcollection.py:10–227  ·  view source on GitHub ↗

Sequence sorted by a key function. SortedCollection() is much easier to work with than using bisect() directly. It supports key functions like those use in sorted(), min(), and max(). The result of the key function call is saved so that keys can be searched efficiently. Instead

Source from the content-addressed store, hash-verified

8from bisect import bisect_left, bisect_right
9
10class SortedCollection(object):
11 '''Sequence sorted by a key function.
12
13 SortedCollection() is much easier to work with than using bisect() directly.
14 It supports key functions like those use in sorted(), min(), and max().
15 The result of the key function call is saved so that keys can be searched
16 efficiently.
17
18 Instead of returning an insertion-point which can be hard to interpret, the
19 five find-methods return a specific item in the sequence. They can scan for
20 exact matches, the last item less-than-or-equal to a key, or the first item
21 greater-than-or-equal to a key.
22
23 Once found, an item's ordinal position can be located with the index() method.
24 New items can be added with the insert() and insert_right() methods.
25 Old items can be deleted with the remove() method.
26
27 The usual sequence methods are provided to support indexing, slicing,
28 length lookup, clearing, copying, forward and reverse iteration, contains
29 checking, item counts, item removal, and a nice looking repr.
30
31 Finding and indexing are O(log n) operations while iteration and insertion
32 are O(n). The initial sort is O(n log n).
33
34 The key function is stored in the 'key' attibute for easy introspection or
35 so that you can assign a new key function (triggering an automatic re-sort).
36
37 In short, the class was designed to handle all of the common use cases for
38 bisect but with a simpler API and support for key functions.
39
40 >>> from pprint import pprint
41 >>> from operator import itemgetter
42
43 >>> s = SortedCollection(key=itemgetter(2))
44 >>> for record in [
45 ... ('roger', 'young', 30),
46 ... ('angela', 'jones', 28),
47 ... ('bill', 'smith', 22),
48 ... ('david', 'thomas', 32)]:
49 ... s.insert(record)
50
51 >>> pprint(list(s)) # show records sorted by age
52 [('bill', 'smith', 22),
53 ('angela', 'jones', 28),
54 ('roger', 'young', 30),
55 ('david', 'thomas', 32)]
56
57 >>> s.find_le(29) # find oldest person aged 29 or younger
58 ('angela', 'jones', 28)
59 >>> s.find_lt(28) # find oldest person under 28
60 ('bill', 'smith', 22)
61 >>> s.find_gt(28) # find youngest person over 28
62 ('roger', 'young', 30)
63
64 >>> r = s.find_ge(32) # find youngest person aged 32 or older
65 >>> s.index(r) # get the index of their record
66 3
67 >>> s[3] # fetch the record at that index

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected