-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue_array.py
More file actions
52 lines (47 loc) · 1.85 KB
/
Copy pathqueue_array.py
File metadata and controls
52 lines (47 loc) · 1.85 KB
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
class Queue:
'''Implements an array-based, efficient first-in first-out Abstract Data Type
using a Python array (faked using a List)'''
def __init__(self, capacity):
self.capacity = capacity
self.items = [None] * capacity
self.front = 2
self.back = 2
self.num_items = 0
#'''Creates an empty Queue with a capacity'''
def is_empty(self):
return self.num_items == 0 and self.capacity != 0
# '''Returns True if the Queue is empty, and False otherwise
# MUST have O(1) performance'''
def is_full(self):
return self.num_items == self.capacity
# '''Returns True if the Queue is full, and False otherwise
# MUST have O(1) performance'''
def enqueue(self, item):
if self.is_full():
raise IndexError
else:
self.items[self.back] = item
self.num_items += 1
self.back += 1
if self.back == self.capacity:
self.back = 0
# '''If Queue is not full, enqueues (adds) item to Queue
# If Queue is full when enqueue is attempted, raises IndexError
# MUST have O(1) performance'''
def dequeue(self):
if self.is_empty():
raise IndexError
else:
front = self.items[self.front]
self.front += 1
self.num_items -= 1
if self.front == self.capacity:
self.front = 0
return front
# '''If Queue is not empty, dequeues (removes) item from Queue and returns item.
# If Queue is empty when dequeue is attempted, raises IndexError
# MUST have O(1) performance'''
def size(self):
return self.num_items
# '''Returns the number of elements currently in the Queue, not the capacity
# MUST have O(1) performance'''