Skip to content

Commit df7b14d

Browse files
committed
Learnt Queue from the book
1 parent 415acbc commit df7b14d

File tree

2 files changed

+114
-93
lines changed

2 files changed

+114
-93
lines changed

.idea/workspace.xml

+51-93
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
class Empty(Exception):
2+
"""Error attempting to access an element from an empty container"""
3+
pass
4+
5+
class ArrayQueue:
6+
"""FIFO Queue implementation using Python list as underlying storage."""
7+
8+
DEFAULT_CAPACITY = 10
9+
10+
def __init__(self):
11+
"""Create an empty queue."""
12+
13+
self._data = [None]*ArrayQueue.DEFAULT_CAPACITY
14+
self._size = 0
15+
self._front = 0
16+
17+
def __len__(self):
18+
"""Return the number of elements in queue."""
19+
return self._size
20+
21+
def is_empty(self):
22+
"""Return True if the queue is empty."""
23+
return self._size == 0
24+
25+
def first(self):
26+
"""Return the element at the front of the queue.
27+
28+
Raise an exception if queue is empty.
29+
"""
30+
if self.is_empty():
31+
raise Empty('Queue is empty')
32+
return self._data[self._front]
33+
34+
def dequeue(self):
35+
"""Remove and return the first element of the queue.
36+
37+
Raise Empty exception is queue is empty.
38+
"""
39+
if self.is_empty():
40+
raise Empty('Queue is empty')
41+
answer = self._data[self._front]
42+
self._data[self._front] = None
43+
self._front = (self._front + 1) % len(self._data)
44+
self._size -= 1
45+
return answer
46+
47+
def enqueue(self, e):
48+
"""Add an element to back of queue."""
49+
if self._size == len(self._data):
50+
self._resize(2 * len(self._data))
51+
avail = (self._size + self._front) % len(self._data)
52+
self._data[avail] = e
53+
self._size += 1
54+
55+
def _resize(self, cap):
56+
"""Resize to a new list of capacity >= len(self)"""
57+
old = self._data
58+
self._data = [None]*cap
59+
walk = self._front
60+
for k in range(self._size):
61+
self._data[k] = old[walk]
62+
walk = (1 + walk) % len(old)
63+
self._front = 0

0 commit comments

Comments
 (0)