Skip to content

Commit 0832e1e

Browse files
Himan10cclauss
authored andcommitted
Adding circular_queue.py (TheAlgorithms#1574)
* Create circular_queue.py Circular Queue implementation using python list with fixed range. * Update circular_queue.py * Update circular_queue.py * Update circular_queue.py * Update circular_queue.py * Update circular_queue.py * doctest: Catch "Exception: UNDERFLOW" * Deal with the fluent interface for cq.enqueue() * Test the fluent interface
1 parent 12f69a8 commit 0832e1e

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
+93
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# Implementation of Circular Queue (using Python lists)
2+
3+
class CircularQueue:
4+
"""Circular FIFO queue with a fixed capacity"""
5+
6+
def __init__(self, n: int):
7+
self.n = n
8+
self.array = [None] * self.n
9+
self.front = 0 # index of the first element
10+
self.rear = 0
11+
self.size = 0
12+
13+
def __len__(self) -> int:
14+
"""
15+
>>> cq = CircularQueue(5)
16+
>>> len(cq)
17+
0
18+
>>> cq.enqueue("A") # doctest: +ELLIPSIS
19+
<circular_queue.CircularQueue object at ...
20+
>>> len(cq)
21+
1
22+
"""
23+
return self.size
24+
25+
def is_empty(self) -> bool:
26+
"""
27+
>>> cq = CircularQueue(5)
28+
>>> cq.is_empty()
29+
True
30+
>>> cq.enqueue("A").is_empty()
31+
False
32+
"""
33+
return self.size == 0
34+
35+
def first(self):
36+
"""
37+
>>> cq = CircularQueue(5)
38+
>>> cq.first()
39+
False
40+
>>> cq.enqueue("A").first()
41+
'A'
42+
"""
43+
return False if self.is_empty() else self.array[self.front]
44+
45+
def enqueue(self, data):
46+
"""
47+
This function insert an element in the queue using self.rear value as an index
48+
>>> cq = CircularQueue(5)
49+
>>> cq.enqueue("A") # doctest: +ELLIPSIS
50+
<circular_queue.CircularQueue object at ...
51+
>>> (cq.size, cq.first())
52+
(1, 'A')
53+
>>> cq.enqueue("B") # doctest: +ELLIPSIS
54+
<circular_queue.CircularQueue object at ...
55+
>>> (cq.size, cq.first())
56+
(2, 'A')
57+
"""
58+
if self.size >= self.n:
59+
raise Exception("QUEUE IS FULL")
60+
61+
self.array[self.rear] = data
62+
self.rear = (self.rear+1)%self.n
63+
self.size += 1
64+
return self
65+
66+
def dequeue(self):
67+
"""
68+
This function removes an element from the queue using on self.front value as an
69+
index
70+
>>> cq = CircularQueue(5)
71+
>>> cq.dequeue()
72+
Traceback (most recent call last):
73+
...
74+
Exception: UNDERFLOW
75+
>>> cq.enqueue("A").enqueue("B").dequeue()
76+
'A'
77+
>>> (cq.size, cq.first())
78+
(1, 'B')
79+
>>> cq.dequeue()
80+
'B'
81+
>>> cq.dequeue()
82+
Traceback (most recent call last):
83+
...
84+
Exception: UNDERFLOW
85+
"""
86+
if self.size == 0:
87+
raise Exception("UNDERFLOW")
88+
89+
temp = self.array[self.front]
90+
self.array[self.front] = None
91+
self.front = (self.front + 1)%self.n
92+
self.size -= 1
93+
return temp

0 commit comments

Comments
 (0)