Created
March 26, 2015 10:35
-
-
Save justinfay/a2a5019b88d5fa60ab53 to your computer and use it in GitHub Desktop.
Ring datatype for Python
This file contains hidden or 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
| def _adj_index(method): | |
| def _dec(instance, *args): | |
| if isinstance(args[0], int): | |
| index = args[0] % len(instance) | |
| return method(instance, index, *args[1:]) | |
| return method(instance, args) | |
| return _dec | |
| class Ring(list): | |
| """ | |
| Ring datatype. | |
| """ | |
| def __iter__(self): | |
| while True: | |
| for i in xrange(len(self)): | |
| yield self[i] | |
| def __getitem__(self, item): | |
| if isinstance(item, tuple): | |
| slice = item[0] | |
| return Ring([ | |
| self[i] | |
| for i in xrange(slice.start, slice.stop, slice.step)]) | |
| return super(Ring, self).__getitem__(item) | |
| __getitem__ = _adj_index(__getitem__) | |
| __setitem__ = _adj_index(list.__setitem__) | |
| __delitem__ = _adj_index(list.__delitem__) | |
| def __getslice__(self, i, j): | |
| return Ring([ | |
| self[x] | |
| for x in range(i, j)]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment