dsa.queue

Module containing queue classes.

  1""" Module containing queue classes. """
  2from dsa.array import CircularArray
  3
  4class Queue:
  5    """ 
  6    A static queue implementation. 
  7    """
  8    def __init__(self, contents=None, capacity: int=10):
  9        """ 
 10        Initialize the queue with a given capacity.
 11
 12        Args:
 13            contents: The list with contents to enqueue.
 14            capacity: The initial size of the stack (defaults to 10).
 15        """
 16        self._array = [None] * capacity
 17        self._front = 0
 18        #: number of elements in queue
 19        self.count = 0
 20
 21        if contents:
 22            for e in contents:
 23                self.enqueue(e)
 24    
 25    def enqueue(self, element):
 26        """
 27        Enqueue an element into the queue. Raise Exception when trying to enqueue more elements than the capacity.
 28
 29        Args:
 30            element: The element to enqueue.
 31
 32        Raises:
 33            Exception: When trying to enqueue more elements than the capacity.
 34
 35        Returns:
 36            None
 37        """
 38        if self.count >= len(self._array):
 39            raise Exception("Capacity Reached")
 40
 41        index = (self._front + self.count) % len(self._array)
 42        self._array[index] = element
 43        self.count += 1
 44        
 45    def dequeue(self):
 46        """
 47        Dequeue an element from the queue. Raise Exception when there are no elements to dequeue.
 48
 49        Raises:
 50            Exception: When there are no elements to dequeue.
 51
 52        Returns:
 53            The from element in the queue.
 54        """
 55        if self.is_empty():
 56            raise Exception("Empty Queue")
 57
 58        element = self._array[self._front]
 59        self._front += 1
 60        if self._front >= len(self._array):
 61            self._front = 0
 62        self.count -= 1
 63
 64        return element
 65    
 66    def peek(self):
 67        """
 68        Return the element in front of the queue. Raise Exception if queue is empty.
 69
 70        Returns:
 71            The element in front of the queue.
 72
 73        Raises:
 74            Exception: When the queue is empty.
 75        """
 76        if self.is_empty():
 77            raise Exception("Empty Queue")
 78
 79        return self._array[self._front]
 80
 81    def is_empty(self):
 82        """
 83        Return a Boolean on whether the stack is empty or not.
 84
 85        Returns:
 86            True if the stack is empty, False otherwise.
 87        """
 88        return self.count == 0
 89    
 90    def capacity(self):
 91        """
 92        Return the capacity of the queue.
 93
 94        Returns:
 95            The capacity of the queue.
 96        """
 97        return len(self._array)
 98    
 99    @classmethod
100    def from_list(cls, alist):
101        """
102        Set the contents of a queue into an array. Raise Exception when trying to enqueue more elements than the capacity.
103
104        Args:
105            alist: The list with contents to enqueue.
106
107        Returns:
108            The queue with the contents of the list.
109        """
110        q = cls()
111        for e in alist:
112            q.enqueue(e)
113        return q
114
115    def to_ordered_list(self) -> list:
116        """
117        Return the contents of the queue as a Python list.
118
119        Returns:
120            The contents of the queue as a Python list.
121        """
122        if self._front + self.count <= len(self._array):
123            return self._array[self._front:self._front + self.count]
124        else:
125            end_part = self._array[self._front:]
126            start_part = self._array[:self._front + self.count - len(self._array)]
127            return end_part + start_part
128        
129    def raw_view(self):
130        """
131        Return the queue in its array representation.
132
133        Returns:
134            The array representation of the queue.
135        """
136        return self._array
137
138    def __repr__(self):
139        """
140        Return a string with details of the queue.
141
142        Returns:
143            A string with details of the queue.
144        """
145        ordered_list = self.to_ordered_list()
146        # arr = []
147        # for i in range(self.count):
148        #     index = (i + self._front) % len(self._array)
149        #     arr.append(str(self._array[index]))
150        arrstr = ", ".join([str(e) for e in ordered_list])
151        return f"[{arrstr}] count: {self.count} Capacity: {self.capacity()}"
152    
153    def __len__(self):
154        """
155        Return the count of items in the queue.
156
157        Returns:
158            The count of items in the queue.
159        """
160        return self.count
161    
162
163class DynamicQueue(Queue):
164    """ 
165    A dynamic queue implementation. Note that shrink is not impelmented.
166    """
167    def __init__(self, contents=None, capacity: int=10):
168        """
169        Initialize the queue with a given capacity.
170        
171        Args:
172            contents: The list with contents to enqueue.
173            capacity: The initial size of the stack (defaults to 10).
174        """
175        super().__init__(contents, capacity)
176    
177    def grow(self):
178        """ 
179        Double the capacity of the current array.
180
181        Returns:
182            None
183        """
184        new_array = [ None ] * len(self._array) * 2
185        
186        # copy elements
187        for i in range(self.count):
188            new_array[i] = self._array[i + self._front]
189        self._front = 0
190        self._array = new_array
191
192    def check_capacity(self):
193        """ 
194        If count >= capacity, grow the array.
195
196        Returns:
197            None
198        """
199        if self._front + self.count >= len(self._array):
200            self.grow()
201
202    def enqueue(self, element):
203        """
204        Enqueue an element into the queue. Increae capacity if count is greater than the capacity.
205
206        Args:
207            element: the element to enqueue
208
209        Returns:
210            None
211        """
212        self.check_capacity()
213        index = self._front + self.count
214        self._array[index] = element
215        self.count += 1
216
217class CircularQueue(CircularArray):
218    """ 
219    A circular queue implementation. 
220    """
221    def __init__(self, contents=None, capacity: int=10):
222        """
223        Initialize the queue with a given capacity.
224
225        Args:
226            contents: The list with contents to enqueue.
227            capacity: The initial size of the stack (defaults to 10).
228        """
229        super().__init__(None, capacity)
230        # self._start is equivalent to the queue's front index
231
232        if contents:
233            for e in contents:
234                self.enqueue(e)
235
236    def enqueue(self, element):
237        """
238        Enqueue an element into the queue. Wrap around when trying to enqueue more elements than the capacity.
239
240        Args:
241            element: The element to enqueue.
242
243        Returns:
244            None
245        """
246        return super().append(element)
247
248    def dequeue(self):
249        """
250        Dequeue an element from the queue. Raise Exception when there are no elements to dequeue.
251
252        Raises:
253            Exception: When there are no elements to dequeue.
254
255        Returns:
256            The from element in the queue.
257        """
258        if self.is_empty():
259            raise Exception("Empty Queue")
260
261        element = self._array[self._start]
262        self._start = (self._start + 1) % len(self._array)
263        self.count -= 1
264        return element
265
266    def peek(self):
267        """
268        Return the element in front of the queue. Raise Exception if queue is empty.
269
270        Returns:
271            The element in front of the queue.
272
273        Raises:
274            Exception: When the queue is empty.
275        """
276        if self.is_empty():
277            raise Exception("Empty Queue")
278
279        return self._array[self._start]
280
281
282 
class Queue:
  5class Queue:
  6    """ 
  7    A static queue implementation. 
  8    """
  9    def __init__(self, contents=None, capacity: int=10):
 10        """ 
 11        Initialize the queue with a given capacity.
 12
 13        Args:
 14            contents: The list with contents to enqueue.
 15            capacity: The initial size of the stack (defaults to 10).
 16        """
 17        self._array = [None] * capacity
 18        self._front = 0
 19        #: number of elements in queue
 20        self.count = 0
 21
 22        if contents:
 23            for e in contents:
 24                self.enqueue(e)
 25    
 26    def enqueue(self, element):
 27        """
 28        Enqueue an element into the queue. Raise Exception when trying to enqueue more elements than the capacity.
 29
 30        Args:
 31            element: The element to enqueue.
 32
 33        Raises:
 34            Exception: When trying to enqueue more elements than the capacity.
 35
 36        Returns:
 37            None
 38        """
 39        if self.count >= len(self._array):
 40            raise Exception("Capacity Reached")
 41
 42        index = (self._front + self.count) % len(self._array)
 43        self._array[index] = element
 44        self.count += 1
 45        
 46    def dequeue(self):
 47        """
 48        Dequeue an element from the queue. Raise Exception when there are no elements to dequeue.
 49
 50        Raises:
 51            Exception: When there are no elements to dequeue.
 52
 53        Returns:
 54            The from element in the queue.
 55        """
 56        if self.is_empty():
 57            raise Exception("Empty Queue")
 58
 59        element = self._array[self._front]
 60        self._front += 1
 61        if self._front >= len(self._array):
 62            self._front = 0
 63        self.count -= 1
 64
 65        return element
 66    
 67    def peek(self):
 68        """
 69        Return the element in front of the queue. Raise Exception if queue is empty.
 70
 71        Returns:
 72            The element in front of the queue.
 73
 74        Raises:
 75            Exception: When the queue is empty.
 76        """
 77        if self.is_empty():
 78            raise Exception("Empty Queue")
 79
 80        return self._array[self._front]
 81
 82    def is_empty(self):
 83        """
 84        Return a Boolean on whether the stack is empty or not.
 85
 86        Returns:
 87            True if the stack is empty, False otherwise.
 88        """
 89        return self.count == 0
 90    
 91    def capacity(self):
 92        """
 93        Return the capacity of the queue.
 94
 95        Returns:
 96            The capacity of the queue.
 97        """
 98        return len(self._array)
 99    
100    @classmethod
101    def from_list(cls, alist):
102        """
103        Set the contents of a queue into an array. Raise Exception when trying to enqueue more elements than the capacity.
104
105        Args:
106            alist: The list with contents to enqueue.
107
108        Returns:
109            The queue with the contents of the list.
110        """
111        q = cls()
112        for e in alist:
113            q.enqueue(e)
114        return q
115
116    def to_ordered_list(self) -> list:
117        """
118        Return the contents of the queue as a Python list.
119
120        Returns:
121            The contents of the queue as a Python list.
122        """
123        if self._front + self.count <= len(self._array):
124            return self._array[self._front:self._front + self.count]
125        else:
126            end_part = self._array[self._front:]
127            start_part = self._array[:self._front + self.count - len(self._array)]
128            return end_part + start_part
129        
130    def raw_view(self):
131        """
132        Return the queue in its array representation.
133
134        Returns:
135            The array representation of the queue.
136        """
137        return self._array
138
139    def __repr__(self):
140        """
141        Return a string with details of the queue.
142
143        Returns:
144            A string with details of the queue.
145        """
146        ordered_list = self.to_ordered_list()
147        # arr = []
148        # for i in range(self.count):
149        #     index = (i + self._front) % len(self._array)
150        #     arr.append(str(self._array[index]))
151        arrstr = ", ".join([str(e) for e in ordered_list])
152        return f"[{arrstr}] count: {self.count} Capacity: {self.capacity()}"
153    
154    def __len__(self):
155        """
156        Return the count of items in the queue.
157
158        Returns:
159            The count of items in the queue.
160        """
161        return self.count

A static queue implementation.

Queue(contents=None, capacity: int = 10)
 9    def __init__(self, contents=None, capacity: int=10):
10        """ 
11        Initialize the queue with a given capacity.
12
13        Args:
14            contents: The list with contents to enqueue.
15            capacity: The initial size of the stack (defaults to 10).
16        """
17        self._array = [None] * capacity
18        self._front = 0
19        #: number of elements in queue
20        self.count = 0
21
22        if contents:
23            for e in contents:
24                self.enqueue(e)

Initialize the queue with a given capacity.

Args: contents: The list with contents to enqueue. capacity: The initial size of the stack (defaults to 10).

count
def enqueue(self, element):
26    def enqueue(self, element):
27        """
28        Enqueue an element into the queue. Raise Exception when trying to enqueue more elements than the capacity.
29
30        Args:
31            element: The element to enqueue.
32
33        Raises:
34            Exception: When trying to enqueue more elements than the capacity.
35
36        Returns:
37            None
38        """
39        if self.count >= len(self._array):
40            raise Exception("Capacity Reached")
41
42        index = (self._front + self.count) % len(self._array)
43        self._array[index] = element
44        self.count += 1

Enqueue an element into the queue. Raise Exception when trying to enqueue more elements than the capacity.

Args: element: The element to enqueue.

Raises: Exception: When trying to enqueue more elements than the capacity.

Returns: None

def dequeue(self):
46    def dequeue(self):
47        """
48        Dequeue an element from the queue. Raise Exception when there are no elements to dequeue.
49
50        Raises:
51            Exception: When there are no elements to dequeue.
52
53        Returns:
54            The from element in the queue.
55        """
56        if self.is_empty():
57            raise Exception("Empty Queue")
58
59        element = self._array[self._front]
60        self._front += 1
61        if self._front >= len(self._array):
62            self._front = 0
63        self.count -= 1
64
65        return element

Dequeue an element from the queue. Raise Exception when there are no elements to dequeue.

Raises: Exception: When there are no elements to dequeue.

Returns: The from element in the queue.

def peek(self):
67    def peek(self):
68        """
69        Return the element in front of the queue. Raise Exception if queue is empty.
70
71        Returns:
72            The element in front of the queue.
73
74        Raises:
75            Exception: When the queue is empty.
76        """
77        if self.is_empty():
78            raise Exception("Empty Queue")
79
80        return self._array[self._front]

Return the element in front of the queue. Raise Exception if queue is empty.

Returns: The element in front of the queue.

Raises: Exception: When the queue is empty.

def is_empty(self):
82    def is_empty(self):
83        """
84        Return a Boolean on whether the stack is empty or not.
85
86        Returns:
87            True if the stack is empty, False otherwise.
88        """
89        return self.count == 0

Return a Boolean on whether the stack is empty or not.

Returns: True if the stack is empty, False otherwise.

def capacity(self):
91    def capacity(self):
92        """
93        Return the capacity of the queue.
94
95        Returns:
96            The capacity of the queue.
97        """
98        return len(self._array)

Return the capacity of the queue.

Returns: The capacity of the queue.

@classmethod
def from_list(cls, alist):
100    @classmethod
101    def from_list(cls, alist):
102        """
103        Set the contents of a queue into an array. Raise Exception when trying to enqueue more elements than the capacity.
104
105        Args:
106            alist: The list with contents to enqueue.
107
108        Returns:
109            The queue with the contents of the list.
110        """
111        q = cls()
112        for e in alist:
113            q.enqueue(e)
114        return q

Set the contents of a queue into an array. Raise Exception when trying to enqueue more elements than the capacity.

Args: alist: The list with contents to enqueue.

Returns: The queue with the contents of the list.

def to_ordered_list(self) -> list:
116    def to_ordered_list(self) -> list:
117        """
118        Return the contents of the queue as a Python list.
119
120        Returns:
121            The contents of the queue as a Python list.
122        """
123        if self._front + self.count <= len(self._array):
124            return self._array[self._front:self._front + self.count]
125        else:
126            end_part = self._array[self._front:]
127            start_part = self._array[:self._front + self.count - len(self._array)]
128            return end_part + start_part

Return the contents of the queue as a Python list.

Returns: The contents of the queue as a Python list.

def raw_view(self):
130    def raw_view(self):
131        """
132        Return the queue in its array representation.
133
134        Returns:
135            The array representation of the queue.
136        """
137        return self._array

Return the queue in its array representation.

Returns: The array representation of the queue.

class DynamicQueue(Queue):
164class DynamicQueue(Queue):
165    """ 
166    A dynamic queue implementation. Note that shrink is not impelmented.
167    """
168    def __init__(self, contents=None, capacity: int=10):
169        """
170        Initialize the queue with a given capacity.
171        
172        Args:
173            contents: The list with contents to enqueue.
174            capacity: The initial size of the stack (defaults to 10).
175        """
176        super().__init__(contents, capacity)
177    
178    def grow(self):
179        """ 
180        Double the capacity of the current array.
181
182        Returns:
183            None
184        """
185        new_array = [ None ] * len(self._array) * 2
186        
187        # copy elements
188        for i in range(self.count):
189            new_array[i] = self._array[i + self._front]
190        self._front = 0
191        self._array = new_array
192
193    def check_capacity(self):
194        """ 
195        If count >= capacity, grow the array.
196
197        Returns:
198            None
199        """
200        if self._front + self.count >= len(self._array):
201            self.grow()
202
203    def enqueue(self, element):
204        """
205        Enqueue an element into the queue. Increae capacity if count is greater than the capacity.
206
207        Args:
208            element: the element to enqueue
209
210        Returns:
211            None
212        """
213        self.check_capacity()
214        index = self._front + self.count
215        self._array[index] = element
216        self.count += 1

A dynamic queue implementation. Note that shrink is not impelmented.

DynamicQueue(contents=None, capacity: int = 10)
168    def __init__(self, contents=None, capacity: int=10):
169        """
170        Initialize the queue with a given capacity.
171        
172        Args:
173            contents: The list with contents to enqueue.
174            capacity: The initial size of the stack (defaults to 10).
175        """
176        super().__init__(contents, capacity)

Initialize the queue with a given capacity.

Args: contents: The list with contents to enqueue. capacity: The initial size of the stack (defaults to 10).

def grow(self):
178    def grow(self):
179        """ 
180        Double the capacity of the current array.
181
182        Returns:
183            None
184        """
185        new_array = [ None ] * len(self._array) * 2
186        
187        # copy elements
188        for i in range(self.count):
189            new_array[i] = self._array[i + self._front]
190        self._front = 0
191        self._array = new_array

Double the capacity of the current array.

Returns: None

def check_capacity(self):
193    def check_capacity(self):
194        """ 
195        If count >= capacity, grow the array.
196
197        Returns:
198            None
199        """
200        if self._front + self.count >= len(self._array):
201            self.grow()

If count >= capacity, grow the array.

Returns: None

def enqueue(self, element):
203    def enqueue(self, element):
204        """
205        Enqueue an element into the queue. Increae capacity if count is greater than the capacity.
206
207        Args:
208            element: the element to enqueue
209
210        Returns:
211            None
212        """
213        self.check_capacity()
214        index = self._front + self.count
215        self._array[index] = element
216        self.count += 1

Enqueue an element into the queue. Increae capacity if count is greater than the capacity.

Args: element: the element to enqueue

Returns: None

class CircularQueue(dsa.array.CircularArray):
218class CircularQueue(CircularArray):
219    """ 
220    A circular queue implementation. 
221    """
222    def __init__(self, contents=None, capacity: int=10):
223        """
224        Initialize the queue with a given capacity.
225
226        Args:
227            contents: The list with contents to enqueue.
228            capacity: The initial size of the stack (defaults to 10).
229        """
230        super().__init__(None, capacity)
231        # self._start is equivalent to the queue's front index
232
233        if contents:
234            for e in contents:
235                self.enqueue(e)
236
237    def enqueue(self, element):
238        """
239        Enqueue an element into the queue. Wrap around when trying to enqueue more elements than the capacity.
240
241        Args:
242            element: The element to enqueue.
243
244        Returns:
245            None
246        """
247        return super().append(element)
248
249    def dequeue(self):
250        """
251        Dequeue an element from the queue. Raise Exception when there are no elements to dequeue.
252
253        Raises:
254            Exception: When there are no elements to dequeue.
255
256        Returns:
257            The from element in the queue.
258        """
259        if self.is_empty():
260            raise Exception("Empty Queue")
261
262        element = self._array[self._start]
263        self._start = (self._start + 1) % len(self._array)
264        self.count -= 1
265        return element
266
267    def peek(self):
268        """
269        Return the element in front of the queue. Raise Exception if queue is empty.
270
271        Returns:
272            The element in front of the queue.
273
274        Raises:
275            Exception: When the queue is empty.
276        """
277        if self.is_empty():
278            raise Exception("Empty Queue")
279
280        return self._array[self._start]

A circular queue implementation.

CircularQueue(contents=None, capacity: int = 10)
222    def __init__(self, contents=None, capacity: int=10):
223        """
224        Initialize the queue with a given capacity.
225
226        Args:
227            contents: The list with contents to enqueue.
228            capacity: The initial size of the stack (defaults to 10).
229        """
230        super().__init__(None, capacity)
231        # self._start is equivalent to the queue's front index
232
233        if contents:
234            for e in contents:
235                self.enqueue(e)

Initialize the queue with a given capacity.

Args: contents: The list with contents to enqueue. capacity: The initial size of the stack (defaults to 10).

def enqueue(self, element):
237    def enqueue(self, element):
238        """
239        Enqueue an element into the queue. Wrap around when trying to enqueue more elements than the capacity.
240
241        Args:
242            element: The element to enqueue.
243
244        Returns:
245            None
246        """
247        return super().append(element)

Enqueue an element into the queue. Wrap around when trying to enqueue more elements than the capacity.

Args: element: The element to enqueue.

Returns: None

def dequeue(self):
249    def dequeue(self):
250        """
251        Dequeue an element from the queue. Raise Exception when there are no elements to dequeue.
252
253        Raises:
254            Exception: When there are no elements to dequeue.
255
256        Returns:
257            The from element in the queue.
258        """
259        if self.is_empty():
260            raise Exception("Empty Queue")
261
262        element = self._array[self._start]
263        self._start = (self._start + 1) % len(self._array)
264        self.count -= 1
265        return element

Dequeue an element from the queue. Raise Exception when there are no elements to dequeue.

Raises: Exception: When there are no elements to dequeue.

Returns: The from element in the queue.

def peek(self):
267    def peek(self):
268        """
269        Return the element in front of the queue. Raise Exception if queue is empty.
270
271        Returns:
272            The element in front of the queue.
273
274        Raises:
275            Exception: When the queue is empty.
276        """
277        if self.is_empty():
278            raise Exception("Empty Queue")
279
280        return self._array[self._start]

Return the element in front of the queue. Raise Exception if queue is empty.

Returns: The element in front of the queue.

Raises: Exception: When the queue is empty.