-
Notifications
You must be signed in to change notification settings - Fork 0
/
356.py
73 lines (53 loc) · 1.87 KB
/
356.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""
Problem:
Implement a queue using a set of fixed-length arrays.
The queue should support enqueue, dequeue, and get_size operations.
"""
from typing import Any
class Queue:
def __init__(self, num_of_arr: int, size_of_arr: int) -> None:
# storing the fixed length arrays as matrix
self.matrix = [[None for _ in range(size_of_arr)] for _ in range(num_of_arr)]
self.size_of_arr, self.num_of_arr = size_of_arr, num_of_arr
self.head_pos, self.rear_pos = 0, 0
def enqueue(self, obj: Any) -> None:
if self.rear_pos == (self.num_of_arr * self.size_of_arr) - 1:
raise OverflowError("Queue is full")
i = (self.rear_pos) // self.size_of_arr
j = (self.rear_pos) % self.size_of_arr
self.matrix[i][j] = obj
self.rear_pos += 1
def dequeue(self) -> Any:
if self.rear_pos == 0:
raise RuntimeError("Queue is empty")
obj = self.matrix[0][0]
# resetting other elements' position
for pos in range(1, self.rear_pos + 1):
i = (pos) // self.size_of_arr
j = (pos) % self.size_of_arr
if j == 0:
self.matrix[i - 1][self.size_of_arr - 1] = self.matrix[i][j]
else:
self.matrix[i][j - 1] = self.matrix[i][j]
self.rear_pos -= 1
return obj
def get_size(self) -> int:
return self.rear_pos
if __name__ == "__main__":
queue = Queue(3, 2)
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print("SIZE:", queue.get_size())
print(queue.dequeue())
print("SIZE:", queue.get_size())
queue.enqueue(4)
print(queue.dequeue())
queue.enqueue(5)
queue.enqueue(6)
print("SIZE:", queue.get_size())
print(queue.dequeue())
print(queue.dequeue())
print(queue.dequeue())
print(queue.dequeue())
print("SIZE:", queue.get_size())