Created
June 21, 2014 02:15
-
-
Save dutc/8b2bde9f179edf577f42 to your computer and use it in GitHub Desktop.
dinky circular buffer
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 import deque | |
class CircularBuffer(deque): | |
def __init__(self, *args, **kwargs): | |
self.size = kwargs.pop('size', 3) | |
super(CircularBuffer, self).__init__(*args, **kwargs) | |
def append(self, item): | |
while len(self) >= self.size: | |
self.popleft() | |
super(CircularBuffer, self).append(item) | |
def extend(self, items): | |
for item in items: | |
self.append(item) | |
def appendleft(self, item): | |
while len(self) >= self.size: | |
self.pop() | |
super(CircularBuffer, self).appendleft(item) | |
def extendleft(self, items): | |
for item in items: | |
self.appendleft(item) | |
if __name__ == '__main__': | |
notes = 'do re mi fa so la ti'.split() | |
buf = CircularBuffer() | |
for note in notes: | |
print buf | |
buf.append(note) | |
buf = CircularBuffer() | |
for note in notes: | |
print buf | |
buf.appendleft(note) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment