Python problem !!! Ring Buffer # Create and return a ring buffer, with the given
ID: 3758749 • Letter: P
Question
Python problem !!! Ring Buffer
# Create and return a ring buffer, with the given maximum capacity and with all # elements initialized to None. A ring buffer is represented as a list # of four elements: the buffer (buff) itself as a list; number of elements # (size) currently in buff; the index (first) of the least recently # inserted item; and the index (last) one beyond the most recently # inserted item. def create(capacity): # Return the number of items currently in the buffer rb.I def size(rb): # Return True if the buffer rb is empty and False otherwise. def is_empty(rb): # Return True if the buffer rb is full and False otherwise. def isfuU(rb): # Add item x to the end of the buffer rb. def enqueue(rb, X): # Delete and return item from the front of the buffer rb. def dequeue(rb): # Return (but do not delete) item from the front of the buffer rb def peek (rb)Explanation / Answer
working python code:
import numpy as np
class rbuff(object):
def __init__(self, size_max, default_value=0.0, dtype=float):
"""initialization"""
self.size_max = size_max
self._data = np.empty(size_max, dtype=dtype)
self._data.fill(default_value)
self.size = 0
def enqueue(self, value):
self._data = np.roll(self._data, 1)
self._data[0] = value
self.size += 1
if self.size == self.size_max:
self.__class__ = rbuffFull
def display(self):
return(self._data)
def peek(self):
return(self.display()[0:self.size])
def __getitem__(self, key):
return(self._data[key])
def __repr__(self):
s = self._data.__repr__()
s = s + ' ' + str(self.size)
s = s + ' ' + self.display()[::-1].__repr__()
s = s + ' ' + self.peek()[::-1].__repr__()
return(s)
class rbuffFull(rbuff):
def enqueue(self, value):
self._data = np.roll(self._data, 1)
self._data[0] = value
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.