Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.5 kB
3
Indexable
Never
class CircularBuffer:
    def __init__(self, size):
        self.size = size
        self.buffer = [None] * size
        self.push_index = 0
        self.pop_index = 0
        self.count = 0

    def push(self, val):
        if self.count == self.size:
            raise Exception("Buffer Size reached")
        
        self.buffer[self.push_index] = val
        self.push_index += 1
        if self.push_index == self.size:
            self.push_index = 0
        self.count += 1

    def pop(self):
        if self.count == 0:
            raise Exception("Buffer Empty")
        
        value = self.buffer[self.pop_index]
        self.pop_index += 1
        if self.pop_index == self.size:
            self.pop_index = 0
        self.count -= 1
        return value

def main():
    obj = CircularBuffer(3)
    operations = [
        ("push", 1), ("push", 2), ("push", 3), 
        ("push", 5),
        ("pop", None), ("push", 6), ("push", 7), ("pop", None),
        ("push", 7), ("pop", None), ("pop", None), ("push", 8),
        ("push", 9)
    ]
    for op, val in operations:
        try:
            if op == "push":
                obj.push(val)
                print(f"Push {val}")
            else:
                pop = obj.pop()
                print(f"Pop {pop}")
        except Exception as e:
            print(f"Error: {e}")

        print(f"Buffer: {obj.buffer}, Push Index: {obj.push_index}, Pop Index: {obj.pop_index}, Count: {obj.count}")
        print("--------------------")

if __name__ == "__main__":
    main()
Leave a Comment