I'm working on implementing a queue using a circular buffer problem. Any smarter ideas for better time complexity, any code bug or code style advice are highly appreciated.
class QueueOnCirciularBuffer:
def __init__(self, max_size):
self.buffer = [0]*max_size
self.index = 0 # element to write
self.size = 0
self.max_size = max_size
def push_element(self, value):
if self.size == self.max_size:
raise Exception('queue full')
self.buffer[self.index] = value
self.index += 1
self.size += 1
self.index = self.index % self.max_size
def pop_element(self):
if self.size > 0:
value = self.buffer[(self.index - self.size+self.max_size)%self.max_size]
self.size -= 1
return value
else:
raise Exception('empty queue')
def peak_element(self):
if self.size > 0:
return self.buffer[(self.index-1+self.max_size)%self.max_size]
else:
raise Exception('empty queue')
if __name__ == "__main__":
q = QueueOnCirciularBuffer(16)
q.push_element(1)
q.push_element(2)
print q.peak_element() # output 2
q.pop_element()
print q.peak_element() # output 2
q2 = QueueOnCirciularBuffer(3)
for i in range(3):
print i
q2.push_element(i)
for i in range(10):
print q2.pop_element()
q2.push_element(i)