Skip to content

Instantly share code, notes, and snippets.

Last active November 22, 2020 13:38
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save honno/576c11df4149ff72405b4048130e02e7 to your computer and use it in GitHub Desktop.
Reference implementation of the data binning container "Bins"
from 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
i = bisect_left(intervals, key)
leftkey = intervals[i - 1]
rightkey = intervals[i]
if abs(leftkey - key) < abs(rightkey - key):
return leftkey
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)})"
Copy link

I believe

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

should be

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

Copy link

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