Last active
November 22, 2020 13:38
-
-
Save honno/576c11df4149ff72405b4048130e02e7 to your computer and use it in GitHub Desktop.
Reference implementation of the data binning container "Bins"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)})" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@mpkocher good shout thanks!