In [1]:
class Queue:
    # Circular List Implementation

    DEFAULT_CAPACITY = 10

    def __init__(self):
        # instance variables: _data, _size, _front
        self._data = [None]*Queue.DEFAULT_CAPACITY
        self._size = 0
        self._front = 0

    def __str__(self):
        # string representation of queue
        return str(self._data)+" FRONT="+str(self._front)+" SIZE="+str(self._size)

    def __len__(self):
        # return length of queue
        return self._size

    def is_empty(self):
        # return True if queue is empty otherwise return False
        return self._size == 0

    def first(self):
        # return first item of queue if it is not empty; otherwise return None
        if self._size == 0:
            return None
        else:
            return self._data[self._front]
    
    def dequeue(self):
        # remove and return first item in queue; return None if queue is empty
        if self._size == 0:
            return None
        else:
            result = self._data[self._front]
            self._data[self._front] = None
            self._size = self._size - 1
            self._front = (self._front + 1)%len(self._data)
            return result
            

    def enqueue(self,e):
        # add item e to the end of queue. If list is full, resize the list by
        # creating a new list of twice the size and moving items from old list 
        # to new list; Do not forget to adjust _size and _front
        if self._size == len(self._data):
            self._resize(2*self._size)
        pos = (self._front+self._size)%len(self._data)
        self._data[pos] = e
        self._size = self._size + 1

    def _resize(self,cap):
        # method to resize
        old = self._data
        self._data = [None]*cap
        pos = self._front
        print("pos=",pos)
        for k in range(self._size):
            self._data[k] = old[pos]
            pos = (pos+1)%len(old)
        self._front = 0
In [2]:
[5]*20
Out[2]:
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
In [3]:
q1 = Queue()
In [4]:
q1.enqueue("Anthony")
In [5]:
q1.enqueue("Barbara")
In [6]:
print(q1)
['Anthony', 'Barbara', None, None, None, None, None, None, None, None] FRONT=0 SIZE=2
In [7]:
q1.enqueue("Charles")
q1.enqueue("David")
q1.enqueue("Ernie")
q1.enqueue("Faith")
q1.enqueue("Gordon")
q1.enqueue("Howard")
q1.enqueue("Ian")
q1.enqueue("Jack")
q1.enqueue("King")
print(q1)
pos= 0
['Anthony', 'Barbara', 'Charles', 'David', 'Ernie', 'Faith', 'Gordon', 'Howard', 'Ian', 'Jack', 'King', None, None, None, None, None, None, None, None, None] FRONT=0 SIZE=11
In [8]:
q1.dequeue()
q1.dequeue()
q1.dequeue()
Out[8]:
'Charles'
In [9]:
print(q1)
[None, None, None, 'David', 'Ernie', 'Faith', 'Gordon', 'Howard', 'Ian', 'Jack', 'King', None, None, None, None, None, None, None, None, None] FRONT=3 SIZE=8
In [ ]: