Sorted Collections in Python
I recently was looking at a making predictions on a graph transaction and required maintaining a sorted collection to implement. After spining my wheels (wasting time and failing to build it myself), I google for a bit and found this amazing library called sortedcontainers that is pure python to boot.
If you didn't know about it previously, check it out. It will make your life easier in the future.
!conda install memory_profiler -n data-structures -y
!conda install sortedcontainers -n data-structures -y
%load_ext autoreload
%load_ext memory_profiler
%autoreload 2
from sortedcontainers import SortedList, SortedDict, SortedSet
l = ['e', 'a', 'c', 'd', 'b']
print(f"List({l})")
sl = SortedList(l)
print(f"{sl}")
sl *= 10_000_000
print(f"count of c: {sl.count('c'):,}")
del sl
%%timeit -n 1 -r 5
%memit
sl = SortedList(['e', 'a', 'c', 'd', 'b'])
sl *= 10_000_000
sl.count('c')
del sl
d = {'c': 3, 'a': 1, 'b': 2}
print(f"Dict({d})")
sd = SortedDict(d)
print(f"{sd}")
print(f"pop last item: {sd.popitem(index=-1)}")
del sd
%%timeit -n 1 -r 5
%memit
sd = SortedDict({'c': 3, 'a': 1, 'b': 2})
sd.popitem(index=-1)
del sd
s = set('abracadabra')
print(f"Set({s})")
ss = SortedSet(s)
print(f"{ss}")
print(f"index of c: {ss.bisect_left('c')}")
del ss
%%timeit -n 1 -r 5
%memit
ss = SortedSet('abracadabra')
ss.bisect_left('c')
del ss