Python circular buffer
This is my OLD blog. I've copied this post over to my NEW blog at:
http://www.saltycrane.com/blog/2007/11/python-circular-buffer/
You should be redirected in 2 seconds.
Here is a simple circular buffer, or ring buffer, implementation in Python. It is a first-in, first-out (FIFO) buffer with a fixed size.
class RingBuffer: def __init__(self, size): self.data = [None for i in xrange(size)] def append(self, x): self.data.pop(0) self.data.append(x) def get(self): return self.dataHere is an example where the buffer size is 4. Ten integers, 0-9, are inserted, one at a time, at the end of the buffer. Each iteration, the first element is removed from the front of the buffer.
buf = RingBuffer(4) for i in xrange(10): buf.append(i) print buf.get()
Here are the results:
[None, None, None, 0] [None, None, 0, 1] [None, 0, 1, 2] [0, 1, 2, 3] [1, 2, 3, 4] [2, 3, 4, 5] [3, 4, 5, 6] [4, 5, 6, 7] [5, 6, 7, 8] [6, 7, 8, 9]
References:
- http://mail.python.org/pipermail/python-dev/2003-April/thread.html#34790
- http://www.wayforward.net/pycontract/examples/circbuf.py
- http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68429
- http://docs.python.org/tut/node7.html#SECTION007120000000000000000
- http://docs.python.org/lib/module-Queue.html
- http://en.wikipedia.org/wiki/Circular_queue
No comments:
Post a Comment