Skip to content

Instantly share code, notes, and snippets.

@honno
Last active November 22, 2020 13:38
Embed
What would you like to do?
Reference implementation of the data binning container "Bins"
from collections.abc import MutableMapping
from bisect import bisect_left
class Bins(MutableMapping):
def __init__(self, intervals):
empty_bins = {interval: 0 for interval in intervals}
self._dict = empty_bins
def __getitem__(self, key):
interval = self._roundkey(key)
return self._dict[interval]
def __setitem__(self, key, value):
interval = self._roundkey(key)
self._dict[interval] = value
def _roundkey(self, key):
intervals = list(self._dict.keys())
minkey = intervals[0]
midkeys = intervals[1:-1]
maxkey = intervals[-1]
if key <= minkey:
return minkey
elif key >= maxkey:
return maxkey
elif key in midkeys:
return key
else:
i = bisect_left(intervals, key)
leftkey = intervals[i - 1]
rightkey = intervals[i]
if abs(leftkey - key) < abs(rightkey - key):
return leftkey
else:
return rightkey
def __delitem__(self, key):
del self._dict[key]
def __iter__(self):
return iter(self._dict)
def __len__(self):
return len(self._dict)
def __repr__(self):
return repr(self._dict)
def __str__(self):
return f"Bins({repr(self)})"
@mpkocher
Copy link

I believe

    def __delitem__(self, key):
        del self._dict

should be

    def __delitem__(self, key):
        del self._dict[key]

@honno
Copy link
Author

honno commented Nov 19, 2020

@mpkocher good shout thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment