Printing Queue - Department of Computer Science

COMPSCI 105 S2 2014
Principles of Computer Science
14 Queues
Agenda & Reading

Agenda







Introduction
Queue Abstract Data Type (ADT)
Implementing a queue using a list
Using the Queue ADT to solve problems
A Circular Queue
The Deque Abstract Data Type
Reading

Textbook: Problem Solving with Algorithms and Data Structures

2
Chapter 3
COMPSCI105
lecture14-15
14.1 Introduction
What is a Queue?


Queues are appropriate for many real-world situations

Example: A line to buy a movie ticket

Computer applications, e.g. a request to print a document
A queue is an ordered collection of items where the
addition of new items happens at one end (the rear or back
of the queue) and the removal of existing items always takes
place at the other end (the front of the queue).

New items enter at the back, or rear, of the queue

Items leave from the front of the queue

First-in, first-out (FIFO) property:

3
The first item inserted into a queue is the first item to leave
COMPSCI105
lecture14-15
14.1 Introduction
More formally…
Queues implement the FIFO (first-in first-out) policy:
e.g. the printer / job queue!
enqueue( o )
dequeue()
front
Rear of the
queue
is_empty()
peek()
4
COMPSCI105
lecture14-15
14.1 Introduction
ADT Queue Operations

What are the operations which can be used with a Stack
Abstract Data?



Create an empty queue:
Determine whether a queue is empty:
Add a new item to the queue:


Remove from the queue the item that was added earliest:


dequeue
Retrieve from the queue the item that was added earliest:

5
enqueue
peek
COMPSCI105
lecture14-15
14.2 The Queue ADT
The Queue Abstract Data Type

Queue() creates a new queue that is empty.


enqueue(item) adds a new item to the rear of the queue.


It needs no parameters and returns a boolean value.
size() returns the number of items in the queue.

6
It needs no parameters and returns the item. The queue is
modified.
is_empty() tests to see whether the queue is empty.


It needs the item and returns nothing.
dequeue() removes the front item from the queue.


It needs no parameters and returns an empty queue.
It needs no parameters and returns an integer.
COMPSCI105
lecture14-15
14.2 The Queue Implementation
In Python

We use a python List data structure to implement the queue.

Remember:


the addition of new items takes place at the beginning of the list
the removal of existing items takes place at the end of the list
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def size(self):
return len(self.items)
def enqueue(self, item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
7
COMPSCI105
Enqueue
(rear of the
queue)
Dequeue
(front of
the queue)
lecture14-15
14.2 The Queue ADT
Code Example – Result

Queue operations, state of the queue, values returned
q = Queue()
8
Enqueue:
(rear of the queue)
(beginning of the list)
q.is_empty()
[]
q.enqueue(4)
[4]
q.enqueue('dog')
['dog',4]
q.enqueue(True)
[True,'dog',4]
q.size()
[True,'dog',4]
3
q.is_empty()
[True,'dog',4]
False
q.enqueue(8.4)
[8.4,True,'dog',4]
q.dequeue()
[8.4,True,'dog']
4
q.dequeue()
[8.4,True]
'dog'
q.size()
[8.4,True]
2
COMPSCI105
True
lecture14-15
14.3 Applications
Example Applications


9
Simulation: Hot Potato
Simulation: Printing Tasks
COMPSCI105
lecture14-15
14.3 Applications
1. Simulation: Hot Potato

Six person game of Hot Potato

10
Children form a circle and pass an item from neighbour to
neighbour as fast as they can. At a certain point in the game, the
action is stopped and the child who has the item (the potato) is
removed from the circle. Play continues until only one child is left.
COMPSCI105
lecture14-15
14.3 Applications
1. Simulation: Hot Potato
Enqueue
(rear of the queue)
Simulation of Hot Potato

hotPotato([Bill, David, Susan, Jane], 3)


1st round:
2nd round:
Bill
Susan
David
1
David
Bill
Susan
2
Susan
David
Bill


3rd round:
Finally
David
11
Jane
Susan
David
Bill
Bill
Jane
Susan
David
1
David
Bill
Jane
Susan
2
Susan
David
Bill
Jane
0
0
Remove
Bill
dequeue
Remove
Jane
0
David
Susan
1
Susan
David
2
David
Susan
COMPSCI105
Remove
Susan
lecture14-15
14.3 Applications
Hot Potato- Code
def hotPotato(namelist, num):
simqueue = Queue()
for name in namelist:
simqueue.enqueue(name)
while simqueue.size() > 1:
for i in range(num):
simqueue.enqueue(simqueue.dequeue())
simqueue.dequeue()
return simqueue.dequeue()
12
COMPSCI105
Move element from the front of
the queue to the end
Return the name when there is only
ONE name remains in the queue
lecture14-15
14.3 Applications
Simulation


Simulation: a technique for modelling the behaviour of both
natural and human-made systems
Goal



An example: Behaviour of a printing tasks – how to optimise?



13
Generate statistics summarising the performance of an existing
system
Predict the performance of a proposed system
Reduce number of complaints from our students about how long
they have to wait for service from a shared printer
Before hiring a faster printer: evaluate the approximate average
time that a student has to wait
To spend a few days and measure with a stopwatch: not an exciting
prospect!
COMPSCI105
lecture14-15
14.3 Applications
2. Printing Tasks

Students send printing tasks to the shared printer, the tasks are
placed in a queue to be processed in a first-come first-served
manner.



=> Build a simulation that models the laboratory:


14
Is the printer capable of handling a certain amount of work?
The slower printing speed could make students wait too long. What page
rate should be used?
enqueue
Students submit printing tasks, we will add them to a waiting list, a queue
of print tasks attached to the printer.
When the printer completes a task, it will look at the queue to see if
there are any remaining tasks to process.
COMPSCI105
lecture14-15
14.3 Applications
Simulation

How to determine when certain events occur?



A time-driven simulation


15
By studying the real world, mathematicians have learned to model
events such as the arrival of tasks using techniques from
probability theory
This statistical information is incorporated into the math model of
the system and is used to generate events reflecting the real world.
Simulated time is advanced by a single time unit
The time of an event, such as an arrival or departure, is determined
randomly and compared with a simulated clock
COMPSCI105
lecture14-15
14.3 Applications
2. Printing Tasks – An Example

Simulation for a period of 1200 seconds



16
Rate: 5 pages per minute
6 printing tasks have been added to the queue.
Average waiting time is 26 sec.
Task
At (current
second)
Number of
pages
Time length
1
190
1
12
2
656
18
216
3
778
8
96
4
906
9
108
5
1136
2
24
6
1193
30
240
COMPSCI105
lecture14-15
from
14.3 Applications
190
An Example
190
Printing
Queue
new
task
190
202
Printing T1
Task 1 created (12 sec)
Added to the printing queue
202
656
Task 2 created (216 sec)
Added to the printing queue
872
778
656
Printing T2
872
906
968
Printing T3
1076
1136
1160
1193
T3
T4
Printing T4
1193
Printing T5
1193
Printing T6
968
COMPSCI105
Removed T3 from the queue
Printing Task 3
Task 4 created (108 sec)
Added to the printing queue
1076
1136
1136
Removed T2 from the queue
Printing Task 2
Task 3 created (96 sec)
Added to the printing queue
906
968
778
Removed T1 from the queue
Printing Task 1
Task1 finished
656
Waiting time:
872-778 = 94
968-906 = 62
description
202
872
17
To
Removed T4 from the queue
Printing Task 4
Task 5 created (24 sec)
Added to the printing queue
1160
Removed T5 from the queue
Printing Task 5
Task 6 created (240 sec)
Added to the printing queue
1433
Removed T6 from the queue
Printing Task 6
lecture14-15
def enqueue(self, item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
14.4 Circular Queue
Circular Queue

What is the Big-O performance of enqueue and dequeue of
the implementation using Python List?

enqueue(…): O(n)



Shifting array elements to the right after each addition – too Expensive!
dequeue() : O(1)
Another Implementation: Circular Queue

enqueue & dequeue : O(1)

Items can be added/removed without shifting the other items in the
process
Viewed as a circle
instead of line
18
COMPSCI105
lecture14-15
14.3 Circular Queue
Set up



Uses a Python list data structure to store the items in the
queue.
The list has an initial capacity (all elements None)
Keeps an index of the current front of the queue and of the
current back of the queue.






19
set front to 0,
set back to MAX_QUEUE – 1,
set count to 0
To initialize the
queue
New items are enqueued at the back index position
Items are dequeued at the front index position.
A count of the queue items to detect queue-full and queueempty conditions
COMPSCI105
lecture14-15
14.3 Circular Queue
How To Advance

Queue-empty:


When either front or back advances past MAX_QUEUE - 1, it
wraps around to 0


front is one slot ahead of back
The wrap-around effect: by using Modulus (%) arithmetic operator
enqueue

If it is not full,
self.back = (self.back + 1) % self.MAX_QUEUE
self.items[self.back] = item
self.count += 1

dequeue

If it is not empty
item = self.items[self.front]
self.front = (self.front + 1) % self.MAX_QUEUE
self.count -= 1
return item
20
COMPSCI105
lecture14-15
14.3 Circular Queue
enqueue(32)
Before:

self.back = (self.back + 1) % self.MAX_QUEUE
self.items[self.back] = item
self.count += 1
enqueue

After:



21
New item is inserted at the position following back
back is advanced by one position
count is incremented by 1
COMPSCI105
lecture14-15
14.3 Circular Queue
dequeue()

Before:

After:



22
item = self.items[self.front]
self.front = (self.front + 1) % self.MAX_QUEUE
self.count -= 1
return item
dequeue
Two spaces left!
Value in front position is removed and returned
front is advanced by 1
count is decremented by 1
COMPSCI105
lecture14-15
14.3 Circular Queue
enqueue(8) and enqueue(50)

Before:
enqueue
Two spaces left!

After:


After running the first enqueue, back = 6
After running the second enqueue, back = 0

23
as the “Back” is wrapped around the list
COMPSCI105
lecture14-15
14.3 Circular Queue
Empty ? Full?


front and back cannot be used to distinguish between
queue-full and queue-empty conditions for a circular array
Case 1:
5
q = Queuecircular(8)
q.enqueue(5)
q.enqueue(2)
q.enqueue(1)
q.enqueue(7)
q.enqueue(9)
q.dequeue()
q.dequeue()
q.dequeue()
q.dequeue()
24
2
q.dequeue()
front = 5
back = 4
COMPSCI105
lecture14-15
14.3 Circular Queue
Empty ? Full?

Case 2:
...
q.enqueue(2)
q.enqueue(4)
q.enqueue(1)
q.enqueue(7)
q.enqueue(6)
q.enqueue(3)
q.enqueue(8)
q.enqueue(9)

is_empty()
front = 5
back = 4
(Same as before)!
return self.count == 0

is_full()
return self.MAX_QUEUE <= self.count
25
COMPSCI105
lecture14-15
14.5 Deque
Abstract Data Type

Deque - Double Ended Queue


26
A deque is an ordered collection of items where items are added
and removed from either end, either front or back.
The newest item is at one of the ends
COMPSCI105
lecture14-15
14.5 Deque
ADT Deque Operations

What are the operations which can be used with a Deque
Abstract Data?




27
Create an empty deque:
Determine whether a deque is empty:
Add a new item to the deque:

add_front()

add_rear()
Remove from the deque the item that was added earliest:

remove_front()

remove_rear()
COMPSCI105
lecture14-15
14.5 Deque
In Python
We use a python List data structure to implement the deque.

class Deque:
def __init__(self):
self.items = []
...
def add_front(self, item):
self.items.append(item)
(rear of the
deque)
def add_rear(self, item):
self.items.insert(0,item)
def remove_front(self):
return self.items.pop()
def remove_rear(self):
return self.items.pop(0)
28
(front of
the deque)
COMPSCI105
lecture14-15
14.5 Deque
Code Example – Result

Deque operations, state of the deque, values returned
d = Deque()
(rear of the
deque)
d.is_empty()
[]
d.add_rear(4)
[4]
d.add_rear('dog')
['dog',4,]
d.add_front('cat')
['dog',4,'cat']
d.add_front(True)
['dog',4,'cat',True]
d.size()
['dog',4,'cat',True]
4
d.is_empty()
['dog',4,'cat',True]
False
d.add_rear(8.4)
[8.4,'dog',4,'cat',True]
d.remove_rear()
['dog',4,'cat',True]
8.4
d.remove_front()
['dog',4,'cat']
True
29
True
(front of
the deque)
COMPSCI105
lecture14-15
14.5 Deque
Big-O Performance

O(1)




def add_rear(self, item):
self.items.insert(0,item)
def remove_front(self):
return self.items.pop()
add_front()
remove_front()
def remove_rear(self):
return self.items.pop(0)
O(n)

def add_front(self, item):
self.items.append(item)
add_rear()
remove_rear()
(rear of the
deque)
(front of
the deque)
30
COMPSCI105
lecture14-15
14.5 Deque
Application: Palindrome Checker

A string which reads the same either left to right, or right to
left is known as a palindrome



31
radar
deed
A dog, a plan, a canal: pagoda.
COMPSCI105
lecture14-15
14.5 Deque
Palindrome Checker - Algorithm

Create a deque to store the characters of the string


The front of the deque will hold the first character of the string
and the rear of the deque will hold the last character
Remove both of them directly, we can compare them and
continue only if they match.

If we can keep matching first and the last items, we will eventually
either run out of characters or be left with a deque of size 1

32
In either case, the string must be a palindrome.
COMPSCI105
lecture14-15
Summary


The definition of the queue operations gives the ADT queue
first-in, first-out (FIFO) behaviour
To distinguish between the queue-full and queue-empty
conditions in a queue implementation that uses a circular
array,


33
count the number of items in the queue
Models of real-world systems often use queues
COMPSCI105
lecture14-15