Created
May 7, 2019 18:07
-
-
Save edwintcloud/df04045bc71a992ff5b3ac4b57c84974 to your computer and use it in GitHub Desktop.
Circular Buffer in Python Part 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def enqueue(self, item): | |
"""Insert an item at the back of the CircularBuffer | |
Runtime: O(1) Space: O(1)""" | |
if self.is_full(): | |
raise OverflowError( | |
"CircularBuffer is full, unable to enqueue item") | |
self.buffer[self.tail] = item | |
self.tail = (self.tail + 1) % self.max_size | |
def dequeue(self): | |
"""Return the item at the front of the Circular Buffer and remove it | |
Runtime: O(1) Space: O(1)""" | |
if self.is_empty(): | |
raise IndexError("CircularBuffer is empty, unable to dequeue") | |
item = self.buffer[self.head] | |
self.buffer[self.head] = None | |
self.head = (self.head + 1) % self.max_size | |
return item | |
def front(self): | |
"""Return the item at the front of the CircularBuffer | |
Runtime: O(1) Space: O(1)""" | |
return self.buffer[self.head] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment