CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday...

53
CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office hours: TR 1-2pm or by appointment. Office location: CI2046. Email: simmondsd[@]uncw.edu

Transcript of CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday...

Page 1: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Queues

1

Devon M. SimmondsUniversity of North Carolina, Wilmington

TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office hours: TR 1-2pm or by appointment. Office location: CI2046. Email: simmondsd[@]uncw.edu

Page 2: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

2

Objectives

After completing this lecture, you will be able to:

•Describe the behavior of a queue from a user’s perspective

•Explain how a queue can be used to support a simulation

•Describe the use of a queue in scheduling processes for computational resources

Page 3: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

3

Objectives (continued)

•Explain the difference between a queue and a priority queue

•Describe a case where a queue would be used rather than a priority queue

•Analyze the performance trade-offs between an array-based implementation of a queue and a linked implementation of a queue

Page 4: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

The Queue ADT

• A queue is a linear list in which items are added at one end of the queue called its rearand removed from the other end called its front.

• The Queue ADT (FIFO)▫ Queue S = {s1 s2 s3 … sN}

▫ Operations: enqueue(item) - adds a new item to the rear of the queue. dequeue():item - removes and return item at the front of the

queue. peek ():item- returns item at the front of the queue, queue is

unchanged. isEmpty() – returns True when the queue is empty. size() - returns the number of items in the queue.

4

Page 5: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

5

Overview of Queues

Page 6: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

6

Overview of Queues (continued)• Insertions are restricted to one end (rear)• Removals are restricted to one end (front)• Queues supports a first-in first-out (FIFO) protocol• Fundamental operations: enqueue and dequeue• Item dequeued, or served next, is always the item

that has been waiting the longest• Priority queue: Higher-priority items are dequeued

first; equal priority items dequeued in FIFO order• Most queues in CS involve scheduling access to

shared resources: CPU/Disk/Printer access

Page 7: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

7

The Queue Interface and Its Use•You can use a Python list to emulate a queue

▫Use append to add an element to rear of queue▫Use pop to remove an element from front of

queue▫Drawback: Queue can be manipulated by all of

the other list operations as well Violate spirit of queue as ADT

•We define a more restricted interface, or set of operations, for any queue implementation and show how these operations are used

Page 8: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

8

Two Applications of Queues

•We now look briefly at two applications of queues:▫One involving computer simulations▫The other involving round-robin CPU

scheduling

Page 9: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

9

Simulations• Computer simulations are used to study behavior

of real-world systems, especially if it is impractical or dangerous to experiment with these systems directly▫Example: Mimic traffic flow on a busy highway

• Another example: Manager of supermarket wants to determine number of checkout cashiers to schedule at various times of the day and must consider:▫Frequency with which new customers arrive▫Number of checkout cashiers available▫Number of items in a customer’s shopping cart▫Period of time considered

Page 10: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

10

Simulations (continued)• Simulations avoid need for formulas by imitating

actual situation and collecting pertinent statistics• Simple technique to mimic variability:

▫Suppose new customers are expected to arrive on average once every four minutes

▫During each minute of simulated time, a program can generate a random number between 0 and 1

▫ If number is less than 1/4, program adds a new customer to a checkout line; otherwise, it does not Probability distribution functions produce more

realistic results

Page 11: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

11

Simulations (continued)• Examples presented involve service providers

and service consumers▫We associate each service provider with a queue

of service consumers• Simulations operate by manipulating these

queues▫At each tick of an imaginary clock, add

consumer(s) to the queues and give consumers at the head of each queue another unit of service

• OO methods can be used to implement simulations

Page 12: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

12

Simulations (continued)• Example: Supermarket simulation

▫A Customer object keeps track of when the customer starts standing in line, when service is first received, and how much service is required

▫A Cashier object has a queue of customer objects▫A simulator object coordinates customer/cashier

activities by doing the following at each clock tick: Generates new customer objects as appropriate Assigns customers to cashiers Tells each cashier to provide one unit of service to

the customer at the head of the queue

Page 13: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

13

Round-Robin CPU Scheduling

•Each process on the ready queue is dequeued in turn and given a slice of CPU time

• Improvement: Can use a priority queue

Page 14: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

14

An Array Implementation

•Array implementation of a queue must access items at the logical beginning and the logical end▫Doing this in computationally effective

manner is complex▫We approach problem in a sequence of

three attempts

Page 15: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

15

A First Attempt• Fixes front of queue at position 0• rear variable points to last item at position n – 1

▫n is the number of items in queue

• Analysis:▫enqueue is efficient O(1)▫dequeue entails shifting all but first item O(n)

for static arrays

Page 16: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

A Python Queue Class (1)

16

# Implementation of a queue ADTclass Queue: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def enqueue(self, item): self.items.append(item) def dequeue(self): return self.items.pop(0)

def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items)

def getQueue(self): return self.items

def main(): s = Queue() print(s.is_empty()) for n in range(7): s.enqueue(n*10) print(s.getQueue())

main()

# front is at position 0

Page 17: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

17

A Second Attempt• Fixes rear of queue at position 0• front variable points to last item at position n –

1▫ n is the number of items in queue

• Analysis:▫ dequeue is efficient O(1)▫ enqueue entails shifting all but first item O(n)

rear of queue front of queue

Page 18: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

A Python Queue Class (1)

18

# Implementation of a queue ADTclass Queue: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def enqueue(self, item): self.items.insert(0, item) def dequeue(self): return self.items.pop()

def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items)

def getQueue(self): return self.items

def main(): s = Queue() print(s.is_empty()) for n in range(7): s.enqueue(n*10) print(s.getQueue())

main()

# rear is at position 0

Page 19: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

19

A Third Attempt•Maintain a second index (front) that points to

item at front of queue▫Starts at 0 and advances as items are dequeued

•Analysis:▫dequeue is O(1)▫Maximum running time of enqueue is O(n)

Page 20: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

20

A Fourth Attempt (non-Python static arrays)• Use a circular array implementation

▫ rear starts at –1; front starts at 0▫ front chases rear pointer through the array▫ When a pointer is about to run off the end of the array, it

is reset to 0

• Running times of enqueue and dequeue are O(1)

Page 21: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

21

A Fourth Attempt (non-Python static arrays) (continued)• What happens when the queue becomes full?

▫Maintain a count of the items in the queue▫When this count equals the size of the array:

Resize▫After resizing, we would like queue to occupy

initial segment of array, with front pointer set to 0 If front pointer is less than rear pointer

Copy positions 0 through size-1 in new array If rear pointer is less than front pointer

Copy positions 0 through size-front and size – front + 1 through size-1 in new array

▫Resizing process is linear

Page 22: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

22

Deques•A dequeue is a double ended queue:

▫It has two ends, front and rear.▫Items can be added at either end.▫Items can be removed from either end.

•The deque ADT add_front(item) - adds a new item to the front of the queue. add_rear(item) - adds a new item to the rear of the queue. remove_front():item - removes and return item at the front

of the queue. remove_rear():item - removes and return item at the rear of

the queue. is_empty() :bool– returns True when the deque is empty. size():int - returns the number of items in the deque.

Page 23: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

23

Deque Application: Palindrome Checker•A palindrome is a string that reads the

same forward and backward.▫Radar, madam▫Marge let a moody baby doom a telegram▫Noel sees Leon

•A deque may to used validate if a string is a palindrome

def pal_checker(a_string): dq = Dequeu() for ch in a_string: dq.add_rear(ch)

still_equal = True while (dq.size() > 1 and still_equal): first = dq.remove_front() last = dq.remove_rear() if(first != last): still_equal = False return still_equal print(pal_checker(“noel sees Leon"))

Page 24: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

24

Priority Queues• A priority queue is a specialized type of queue

▫ Items added to queue are assigned an order of rank

▫ Items of higher priority are removed before those of lower priority

▫ Items of equal priority are removed in FIFO order▫ Item A has a higher priority than item B if A < B▫Objects that recognize the comparison operators

can be ordered in priority queues If not, object can be wrapped with a priority number

in another object that does recognize these operators

Page 25: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

25

Priority Queues (continued)

Page 26: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC23126

Page 27: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC23127

ClassesA Python class uses variables to store data fields and defines methods to perform actions. Additionally, a class provides a special type method, known as initializer, which is invoked to create a new object. An initializer can perform any action, but initializer is designed to perform initializing actions, such as creating the data fields of objects.

class ClassName: initializer methods

Page 28: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC23128

Constructing ObjectsOnce a class is defined, you can create objects from the class by using the following syntax, called a constructor:

className(arguments)

object Data Fields:

__init__(self, …)

2. It invokes the class’s __init__ method to initialize the object. The self parameter in the __init__ method is automatically set to reference the object that was just created.

1. It creates an object in the memory for the class.

Page 29: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC23129

Instance Methods

Methods are functions defined inside a class. They are invoked by objects to perform actions on the objects. For this reason, the methods are also called instance methods in Python. You probably noticed that all the methods including the constructor have the first parameter self, which refers to the object that invokes the method. You can use any name for this parameter. But by convention, self is used.

Page 30: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC23130

Accessing ObjectsAfter an object is created, you can access its data fields and invoke its methods using the dot operator (.), also known as the object member access operator. For example, the following code accesses the radius data field and invokes the getPerimeter and getArea methods.

>>> from Circle import Circle>>> c = Circle(5)>>> c.getPerimeter()31.41592653589793>>> c.radius = 10>>> c.getArea()314.1592653589793

Page 31: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC23131

Why self?Note that the first parameter is special. It is used in the implementation of the method, but not used when the method is called. So, what is this parameter self for? Why does Python need it?

self is a parameter that represents an object. Using self, you can access instance variables in an object. Instance variables are for storing data fields. Each object is an instance of a class. Instance variables are tied to specific objects. Each object has its own instance variables. You can use the syntax self.x to access the instance variable x for the object self in a method.

Page 32: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Classes & UML

• Design is an important part of software development.

• Without proper design, programs tend to be error prone.

• UML – the Unified Modeling Language, is a graphical language for software design.

32

StudentId:IntegerAddr:String

graduate(term:String):int

A UML class Corresponding Python classclass Student ():def __init__(id):

self.id = id #integer self.addr = Address()

def graduate (term):#code here

Page 33: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC23133

Example: Defining Classes and Creating Objects

TV

channel: int

volumeLevel: int

on: bool

TV()

turnOn(): None

turnOff(): None

getChannel(): int

setChannel(channel: int): None

getVolume(): int

setVolume(volumeLevel: int): None

channelUp(): None

channelDown(): None

volumeUp(): None

volumeDown(): None

The current channel (1 to 120) of this TV.

The current volume level (1 to 7) of this TV.

Indicates whether this TV is on/off.

Constructs a default TV object.

Turns on this TV.

Turns off this TV.

Returns the channel for this TV.

Sets a new channel for this TV.

Gets the volume level for this TV.

Sets a new volume level for this TV.

Increases the channel number by 1.

Decreases the channel number by 1.

Increases the volume level by 1.

Decreases the volume level by 1.

Page 34: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC23134

The datetime Class

from datetime import datetimed = datetime.now()print("Current year is " + str(d.year))print("Current month is " + str(d.month))print("Current day of month is " + str(d.day))print("Current hour is " + str(d.hour))print("Current minute is " + str(d.minute))print("Current second is " + str(d.second))

Page 35: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC23135

Public and Private Class MembersTo protect data.To make class easy to maintain.

1. To prevent direct modifications of data fields2. don’t let the client directly access data fields. 3. This is known as data field encapsulation. 4. This can be done by defining private data fields.

a. In Python, the private data fields are defined with two leading underscores.

5. You can also define a private method named with two leading underscores.

Page 36: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC23136

Data Field Encapsulation

>>> from CircleWithPrivateRadius import Circle>>> c = Circle(5)>>> c.__radiusAttributeError: 'Circle' object has no attribute '__radius'>>> c.getRadius() 5

# Part of the Circle classclass Circle():

def __init__(radius):self.__radius = radius #other code here

Page 37: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC23137

Design Guide

If a class is designed for other programs to use, to prevent data from being tampered with and to make the class easy to maintain, define data fields private. If a class is only used internally by your own program, there is no need to encapsulate the data fields.

Page 38: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC23138

Designing a Loan Class

Loan

-annualInterestRate: float

-numberOfYears: int

-loanAmount: float

-borrower: str

Loan(annualInterestRate: float, numberOfYear: int, loanAmount: float, borrower: str)

The annual interest rate of the loan (default: 2.5).

The number of years for the loan (default: 1)

The loan amount (default: 1000).

The borrower of this loan.

Constructs a Loan object with the specified annual interest rate, number of years, loan amount, and borrower.

The get methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.

The – sign denotes a private data field.

Page 39: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

39

Case Study: Simulating a Supermarket Checkout Line• Request:

▫ Write program that allows user to predict behavior of supermarket checkout line under various conditions

• Analysis:

Page 40: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

40

Case Study: Simulating a Supermarket Checkout Line (continued)•The Interface:

•Classes and responsibilities:▫We divide the system into a main function

and several model classes

Page 41: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

41

Case Study: Simulating a Supermarket Checkout Line (continued)

Page 42: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

42

Case Study: Simulating a Supermarket Checkout Line (continued)

Page 43: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

43Case Study: Simulating a Supermarket Checkout Line

(continued)

Page 44: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

44

Case Study: An Emergency Room Scheduler•Request:

▫Write a program that allows a supervisor to schedule treatments for patients coming into emergency room

▫Patients are assigned a priority when admitted Higher priority patients receive attention

first•Analysis:

▫Patient priorities: critical, serious, and fair

Page 45: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

45

Case Study: An Emergency Room Scheduler (continued)

Page 46: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

46Case Study: An Emergency Room

Scheduler (continued)

Page 47: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

47

Case Study: An Emergency Room Scheduler (continued)•Classes:

•Design and Implementation:▫Patient and Condition classes maintain a

patient’s name and condition▫Patients can be compared (according to

their conditions) and viewed as strings

Page 48: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

48

Case Study: An Emergency Room Scheduler (continued)

Page 49: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

49

Summary•A queue is a linear collection that adds

elements to the “rear” and removes them from the “front”

•Queues are used in applications that manage data items in a first-in, first-out order (FIFO)▫Example: Scheduling items for processing or

access to resources•Arrays and singly linked structures support

simple implementations of queues•Priority queues schedule their elements using

a rating scheme as well as a FIFO order

Page 50: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC23150

______________________Devon M. Simmonds

Computer Science Department

University of North Carolina Wilmington

_____________________________________________________________

Qu es ti ons?

Reading for next class?

Page 51: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

51

Priority Queues (continued)

•Wrapper class used to build a comparable item from one that is not already comparable:

Page 52: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

52

Priority Queues (continued)•During insertions, a priority queue does not

know whether it is comparing items in wrappers or just items

•When a wrapped item is accessed (e.g., with peek or dequeue), it must be unwrapped with the method getItem before processing

•Two implementations: Sorted linked list or heap

Page 53: CSC 231 Queues 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Fundamentals of

Python: From First Programs Through

Data Structures

53

Search is linear, so enqueue is now O(n)

Priority Queues (continued)