Python Queue Basics for Students
Python Queue Basics for Students
C
                       4                Queue
                    In this Chapter
                    »» Introduction to Queue
                    »» Operations on Queue
                    »» Implementation of Queue        4.1 Introduction         to   Queue
                       using Python
                                                      In the previous chapter we learned about a data
                    »» Introduction to Deque          structure called Stack, which works on Last-In-
                    »» Implementation of Deque        First-Out (LIFO) principle. In this chapter, we will
                       using Python                   learn about another data structure called Queue
                                                      which works on First-In-First-Out (FIFO) principle.
                                                      Queue is an ordered linear list of elements, having
                                                                                different ends for adding
                                                                                and removing elements
                                    Cashier                       Next          in it.
                                                                                         Examples of queue in
                                                                                      our everyday life include
                                                                                      students standing in
                                                                                      a queue for morning
                                                                                      assembly,      customers
                                                                                      forming a queue at the
                                                                                      cash counter in a bank
                                                                                      (Figure 4.1), vehicles
                                                                                      queued at fuel pumps
                                Figure 4.1:	 Queue of people at a bank                (Figure 4.2), etc.
                                                              2020-21
Chapter-4.indd 53                                                                                                     11-09-2020 14:46:23
                     Notes
                                          2020-21
Chapter-4.indd 54                                                                             11-09-2020 14:46:23
                (B)	 Following are some examples of application of
                queue in computer science:
                •	 Suppose there is a web-server hosting a web-site to
                   declare result(s). This server can handle a maximum
                   of 50 concurrent requests to view result(s). So, to
                   serve thousands of user requests, a Queue would be
                   the most appropriate data structure to use.
                •	 Some Operating Systems (OS) are required to handle
                   multiple tasks called - jobs, seeking to use the
                   processor. But we know that a processor can handle
                   only one task at a time. Therefore, in a multitasking    In the web-server
                                                                            example (for result
                   operating system, jobs are lined up (queued) and then
                                                                            declaration), suppose
                   given access to the processor according to some order.   the server receives
                   The simplest way is to give access to the processor on   a request from an
                   a FIFO basis, that is according to the order in which    Administrator to
                   the jobs arrive with a request for the processor.        access the result of a
                                                                            school on an urgent
                •	 When we send print commands from multiple files          basis, along with
                   from the same computer or from different computers       other requests from
                                                                            students to check
                   using a shared printer. The OS puts these print          individual results.
                   requests in a queue and sends them to the printer        Can you suggest some
                   one by one on a FIFO basis.                              strategy to ensure
                                                                            service to all as per
                                                                            their urgency?
                4.2 Operations    on   Queue
                Following the FIFO approach, data structure queue
                supports the following operations:
                •	 ENQUEUE: is used to insert a new element to the
                   queue at the rear end. We can insert elements in
                   the queue till there is space in the queue for adding
                   more elements. Inserting elements beyond capacity
                   of the queue will result in an exception - known as
                   Overflow.
                •	 DEQUEUE: is used to remove one element at a time
                   from the front of the queue. We can delete elements
                   from a queue until it is empty, trying to delete an
                   element from an empty queue will result in exception
                   - known as Underflow.
                  To perform enqueue and dequeue efficiently on a
                queue, following operations are also required:
                •	 IS EMPTY : used to check whether the queue has any
                   element or not, so as to avoid Underflow exception
                   while performing dequeue operation.
Queue 55
                                                       2020-21
Chapter-4.indd 55                                                                                     11-09-2020 14:46:23
                                          •	 PEEK : used to view elements at the front of the queue,
                                             without removing it from the queue.
                       While using a
                     list to implement    •	 IS FULL : used to check whether any more elements
                       queue, we can         can be added to the queue or not, to avoid Overflow
                      designate either       exceptions while performing enqueue operation.
                       end of the list
                     as Front or Rear       Figure 4.3 shows the various stages of a simple
                        of the queue.     queue containing alphabets. In the figure, Front of the
                       But we have to
                                          queue is on the left and Rear on the right.
                      fix either of the
                        ends index[0]
                                           Operation performed        Status of queue after operation
                      or index[n-1] as
                     Front and fix the          enqueue(z)            F     Z     R
                      opposite end as
                            Rear.               enqueue(x)            F     Z     X    R
enqueue(c) F Z X C R
dequeue() F X C R
enqueue(v) F X C V R
dequeue() F C V R
dequeue() F V R
                                                        2020-21
Chapter-4.indd 56                                                                                          11-09-2020 14:46:24
                    creation of list having fixed size. Hence, we will never
                    encounter a situation when the queue is full.
                •	 A function (isEmpty) to check, if the queue has an
                   element or not? This can be done by checking the
                   length of the queue. The function has a parameter
                   -- name of the queue and returns True if the queue
                   is empty False otherwise.
                        def isEmpty(myQueue):
                           	 if len(myQueue)==0:
                             		     return True                                       Can you implement a
                                                                                      queue data structure
                         	    else:
                                                                                      using tuple or
                               	    return False                                      dictionary?
                •	 A function (dequeue) to delete an element from the
                   front of the queue. It has one parameter - name
                   of the queue and returns the deleted element. The
                   function first checks if the queue is empty or not, for
                   successful deletion.
                        def dequeue(myQueue):
                        	    if not (isEmpty(myQueue)):
                           		      return myQueue.pop(0)
                        	    else :
                           		      print(“Queue is empty”)
                Note: The pop() function with index[0] will delete the element from
                the beginning of the list, hence Front of queue.
                •	 A function (size) to get the number of elements in
                   the queue. We can use the len() function of Python’s
                   list to find the number of elements in the queue. The
                   function has one parameter - name of the queue and
                   returns the number of elements in the queue.
                        def size(myQueue):
                            return len(myQueue)
                •	 A function (peek) to simply read, but not to delete,
                   the element at the front end of the queue. For this,
                   we can read the element at index[0] of the queue.                      While choosing
                   The function has one parameter - name of the queue                   the name of above
                                                                                         functions general
                   and returns the value of element at Front if queue is                naming convention
                   not empty, None otherwise.                                           w.r.t. the queue is
                        def peek(myQueue):                                              followed. As these
                            if isEmpty(myQueue):                                          are user defined
                                                                                           functions any
                                   print('Queue is empty')                                other name can
                            	     return None                                              also be used.
                            else:
                                     return myQueue[0]
Queue 57
                                                             2020-21
Chapter-4.indd 57                                                                                              11-09-2020 14:46:24
                         Activity 4.1            Let us consider the example of a queue that people
                    How can you avoid        form while waiting at a bank cash counter. Usually,
                    printing of None,        following are the events that occur in queue:
                    when trying to           •	 Two friends come together and go to the cash
                    print an empty
                    queue?                      counter, i.e. they form a queue - enqueue operation
                                                is performed two times.
                                             •	 As soon as the person at the front is serviced, he will
                                                be removed from the queue - thus dequeue operation
                                                is performed. Cashier calls Next to serve the next
                         Activity 4.2
                                                person who is now at the front of the queue.
                    What if the content of
                    the complete queue       •	 Cashier wants to know the length of the queue - size
                    is to be listed?            of the queue is checked.
                    Write a function
                    for it.                  •	 Meanwhile, a few more people walk in the bank, and
                                                three of them join the queue at the cash counter, i.e.
                                                enqueue happens 3 times.
                                             •	 Another person gets served and leaves the counter,
                                                i.e. dequeue is performed. Cashier calls Next to serve
                                                another person.
                                             •	 The Next three people get served one after another,
                                                i.e. dequeue is performed thrice.
                                             •	 Cashier calls Next and realises that there are no more
                                                people to be served - underflow situation happens
                                                Now, let us write the code for the above scenario of
                                             the bank.
                Program 4-1
                      myQueue = list()
                      # each person to be assigned a code as P1, P2, P3,...
                      element = input("enter person’s code to enter in queue :”)
                      enqueue(myQueue,element)
                      element = input("enter person’s code for insertion in queue :")
                      enqueue(myQueue,element)
                      print("person removed from queue is:", dequeue(myQueue))
                      print(“Number of people in the queue is :”,size(myQueue))
                      element = input("enter person’s code to enter in queue :")
                      enqueue(myQueue,element)
                      element = input("enter person’s code to enter in queue :")
                      enqueue(myQueue,element)
                      element = input("enter person’s code to enter in queue :")
                      enqueue(myQueue,element)
                                                         2020-21
Chapter-4.indd 58                                                                                        11-09-2020 14:46:24
                         print("Now we are going to remove remaining people from the
                         queue")
                         while not isEmpty(myQueue):
                         	    print("person removed from queue is ",
                         	dequeue(myQueue))
                    	Output
                         enter person’s code        to enter in queue :P1
                         enter person’s code        to enter in queue :P2
                         person removed from        the queue is :p1
                         number of people in        the queue is :1
                         enter person’s code        to enter in queue :P3
                         enter person’s code        to enter in queue :P4
                         enter person’s code        to enter in queue :P5
                         Now we are going to        remove remaining people from the queue
                         person removed from        the queue is :p2
                         person removed from        the queue is :p3
                         person removed from        the queue is :p4
                         person removed from        the queue is :p5
                         Queue is empty
Front Rear
Figure 4.4: Basic deque structure displaying head and tail to implement stack or queue.
Queue 59
                                                               2020-21
Chapter-4.indd 59                                                                                                    11-09-2020 14:46:24
                                                   something. As they have already purchased a ticket,
                                                   they may have the privilege to join the queue from
                                                   the front.
                                                •	 Vehicles in a highway toll tax booth are served
                                                   following the principle of queue. There are multiple
                                                   queues if there are parallel booths at the toll gate. In
                                                   case all vehicles of a booth are served then vehicles
                                                   from the other booth(s) are asked to form a queue in
                                                   front of the vacant booth. So, vehicles at the end of
                                                   those queues will leave (removed from the end from
                                                   where queue was joined) current booth and join
                          Activity 4.3             queue at the vacant booth.
                    In a deque, if insertion       Following are some examples where data structure
                    and deletion of
                                                deque maybe applied in computer science:
                    elements is done from
                    the same end, it will       •	 To maintain browser history (URL), usually a stack
                    behave as                      is used, because once a tab is closed and if you press
                    1)	Queue                       ctrl+shift+T, the most recently closed URL is opened
                    2)	Stack
                                                   first. As the number of URLs which can be stored in
                    3)	List
                    4)	None of the                 history is fixed, so when this list of URLs becomes
                       above                       large, URLs from the end of the list (i.e. which were
                                                   least visited) gets deleted.
                                                •	 Same happens for providing the Do and Undo option
                                                   in any text editor.
                                                •	 To check whether a given string is palindrome or not?
                          Activity 4.4             Process string left to right (character wise) and insert
                    In a deque, if insertion
                                                   it in deque from tail/rear like a normal queue. Once
                    and deletion of                the entire string is processed (i.e. inserted in deque)
                    elements is done from          we will take out (delete) a character from both the
                    the opposite end, it will      ends and match them till there is no character left
                    behave as                      or only one character left in deque. In either case,
                    1)	Queue                       string is palindrome.
                    2)	Stack
                    3)	List
                    4)	None of the
                                                4.4.2 Operations on Deque
                       above                    •	 INSERTFRONT: This operation is used to insert a
                                                   new element at the front of the deque.
                                                •	 INSERTREAR: This operation is the same as a
                                                   normal queue, i.e. insert a new element at the rear
                                                   of the deque.
                                                •	 DELETIONFRONT: This operation is the same as
                                                   normal queue, i.e. to remove an element from the
                                                   front of the deque.
                                                •	 DELETIONREAR: This operation is used to remove
                                                   one element at a time from the rear of the deque.
                                                             2020-21
Chapter-4.indd 60                                                                                            11-09-2020 14:46:24
                  To perform above operations efficiently on a deque,                 Notes
                we will need all supporting operations used in normal
                queue viz Is Empty, Peek, Size.
                   Let’s understand how these operations work for
                checking whether a string is palindrome or not, using a
                deque through the following algorithm.
                Algorithm 4.1
                            m     a      d        a              insertrear
                                                                    (m)
                          Front                  Rear
                          Figure 4.5:	 Status of Deque after 4th iteration
                        removefront          a        d    a       insertrear
                           (m)                                        (m)
                                         Front            Rear
                Figure 4.6:	 Status of Deque after removing one character from both
                                              the ends.
Queue 61
                                                                 2020-21
Chapter-4.indd 61                                                                              11-09-2020 14:46:24
                     Notes   •	 A statement to create deque, with name myDeque.
                                   myDeque = list()
                                          2020-21
Chapter-4.indd 62                                                                        11-09-2020 14:46:24
                    function accepts deque as argument and returns a   Notes
                    copy of value, when the queue is not empty.
                        def  getRear(mydeque):
                            if not (isempty()):
                          	   return mydeque[len(mydeque)-1]
                            else :
                          	   print(“ Deque empty”)
                  Let us write a main(), function to invoke various
                Deque functions :
                    def insertFront(myDeque,element):
                    	    myDeque.insert(0,element)
                    def getFront(myDeque):
                    	    if not (isEmpty(myDeque)):
                    		         return myDeque[0]
                    	    else:
                    	 	        print("Queue underflow")
                    def getRear(myDeque):
                    	    if not (isEmpty(myDeque)):
                    		         return myDeque[len(myDeque)-1]
                    	    else:
                    	 	        print ("Queue underflow")
                    def insertRear(myDeque,element):
                    	    myDeque.append(element)
                    def isEmpty(myDeque):
                    	    if len(myDeque) == 0:
                    		         return True
                    	    else:
                    		         return False
                    def deletionRear(myDeque):
                    	    if not isEmpty(myDeque):
                    		         return myDeque.pop()
                    	    else:
                    	 	        print("Queue overflow")
                    def deletionFront(myDeque):
                    	    if isEmpty(myDeque):
Queue 63
                                                      2020-21
Chapter-4.indd 63                                                               11-09-2020 14:46:24
                     	 	          print("Queue underflow")
                     	       else:
                     		            return myDeque.pop(0)
                     def main():
                     	      dQu = list()
                     	      choice = int(input('enter 1 to use as normal queue 2 otherwise
                     		       : '))
                     	      if choice == 1:
                     		          element = input("data for insertion at rear ")
                     		          insertRear(dQu,element)
                       		        element = getFront(dQu)
                     		          print("data at the beginning of queue is ", element)
                          	      element = input("data for insertion at front ")
                     		          insertRear(dQu,element)
                     		          print('data removed from front of queue is ', deletionFront(dQu))
                     		          print('data removed from front of queue is ', deletionFront(dQu))
                    Output
                     enter 1 to use as normal queue 2 otherwise : 1
                     data for insertion at rear    23
                     data at the beginning of queue is    23
                     data for insertion at rear   45
                     data removed from front of queue is     23
                     data removed from front of queue is     45
                     Queue underflow
                     data removed from front of queue is     None
                                            Summary
                                             •	 Queue is an ordered linear data structure,
                                                following FIFO strategy.
                                             •	 Front and Rear are used to indicate beginning
                                                and end of queue.
                                             •	 In Python, the use of predefined methods takes
                                                care of Front and Rear.
                                                      2020-21
Chapter-4.indd 64                                                                                    11-09-2020 14:46:24
                    •	 Insertion in a queue happens at the rear end.                       Notes
                       Deletion happens at the front.
                    •	 Insertion operation is known as enqueue and
                       deletion operation is known as dequeue.
                    •	 To support enqueue and dequeue operations,
                       isEmpty, isfull and peek operations are used
                    •	 Deque is a version of queue, which allows insertion
                       and deletion at both ends.
                    •	 A deque can support both stack and queue
                       operations.
                    •	 Other operations supported by deque are
                       insertfront, insertrear, deletefront, deleterear,
                       getfront, getrear, isempty and isfull.
                         Exercise
                    1.	 Fill in the blank
                        a)	 ____________________ is a linear list of elements
                            in which insertion and deletion takes place from
                            different ends.
                       b)	 Operations on a queue               are    performed      in
                           __________________ order.
                       c)	 Insertion operation in a queue is called ______________
                           and deletion operation in a queue is called
                           ____________________.
                       d)	 Deletion of elements is performed from _______________
                           end of the queue.
                       e)	 Elements ‘A’,’S’,’D’ and ‘F’ are present in the queue, and
                           they are deleted one at a time, ________________________
                           is the sequence of element received.
                       f)	 _______________ is a data structure where elements
                           can be added or removed at either end, but not in the
                           middle.
                       g)	 A deque contains ‘z’,’x’,’c’,’v’ and ‘b’ . Elements
                           received after deletion are ‘z’,’b’,’v’,’x’ and ‘c’. ________
                           __________________________ is the sequence of deletion
                           operation performed on deque.
Queue 65
                                                                 2020-21
Chapter-4.indd 65                                                                                   11-09-2020 14:46:25
                     Notes   4.	 Write a menu driven python program using queue, to
                                 implement movement of shuttlecock in it’s box.
                                          2020-21
Chapter-4.indd 66                                                                          11-09-2020 14:46:25