Last active
January 17, 2019 01:02
-
-
Save gaul/1ae381381b5d2447e671aefc8d2d5ac5 to your computer and use it in GitHub Desktop.
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
#!/bin/env/python3 | |
class CircularBuffer: | |
def __init__(self, capacity): | |
self.array = [None] * capacity | |
self.used = 0 | |
self.index = 0 | |
def push(self, elem): | |
if self.used == len(self.array): | |
return False | |
self.array[(self.index + self.used) % len(self.array)] = elem | |
self.used += 1 | |
return True | |
def pop(self): | |
if self.used == 0: | |
raise IndexError("empty buffer") | |
elem = self.array[self.index] | |
self.index = (self.index + 1) % len(self.array) | |
self.used -= 1 | |
return elem | |
def main(): | |
buf = CircularBuffer(4) | |
try: | |
buf.pop() | |
raise AssertionError() | |
except IndexError as e: | |
pass | |
assert buf.push(1) | |
assert buf.push(2) | |
assert buf.push(3) | |
assert buf.push(4) | |
assert not buf.push(5) | |
assert buf.pop() == 1 | |
assert buf.pop() == 2 | |
assert buf.pop() == 3 | |
assert buf.pop() == 4 | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment