-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathring_buffer.py
More file actions
40 lines (28 loc) · 932 Bytes
/
ring_buffer.py
File metadata and controls
40 lines (28 loc) · 932 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class RingBuffer:
def __init__(self, capacity):
self.capacity = capacity
self.storage = []
self.oldest_index = 0
def append(self, item):
if len(self.storage) < self.capacity:
self.storage.append(item)
else:
self.storage[self.oldest_index] = item
if self.oldest_index < len(self.storage) - 1:
self.oldest_index += 1
else:
self.oldest_index = 0
def get(self):
return self.storage
# buffer = RingBuffer(3)
# buffer.get() # should return []
# buffer.append('a')
# buffer.append('b')
# buffer.append('c')
# buffer.get() # should return ['a', 'b', 'c']
# # 'd' overwrites the oldest value in the ring buffer, which is 'a'
# buffer.append('d')
# buffer.get() # should return ['d', 'b', 'c']
# buffer.append('e')
# buffer.append('f')
# buffer.get() # should return ['d', 'e', 'f']