Scott David Daniels wrote:
Dr. Pastor wrote: Scott David Daniels wrote: Dr. Pastor wrote:
I need a row of 127 bytes that I will use as a
circular buffer. Into the bytes (at unspecified times)
a mark (0<mark<128) will be written, one after the other.
After some time the "buffer" will contain the last 127 marks.
Sounds a lot like homework.
No it is not home work.
OK, taking you at your word, here's one way:
(and some untested code)
As penance for posting untested code, here is a real implementation:
import array
class Circular(object):
'''A circular buffer, holds only non-zero entries'''
def __init__(self, size=127):
'''Create as N-long circular buffer
.data is the circular data store.
.point is the index of the next value to write
'''
self.data = array.array('b', [0] * size)
self.point = 0
def mark(self, value):
'''Add a single value (non-zero) to the buffer'''
assert value
self.data[self.point] = value
self.point += 1
if self.point >= len(self.data):
self.point = 0
def recent(self):
'''Return the most recent values saved.'''
result = self.data[self.point :] + self.data[: self.point]
for n, v in enumerate(result):
if v:
return result[n :]
return result[: 0] # an empty array
Tests:
c = Circular(3)
assert list(c.recent()) == []
c.mark(12)
assert list(c.recent()) == [12]
c.mark(11)
assert list(c.recent()) == [12, 11]
c.mark(10)
assert list(c.recent()) == [12, 11, 10]
c.mark(9)
assert list(c.recent()) == [11, 10, 9]
--Scott David Daniels
sc***********@acm.org