Upload
others
View
12
Download
0
Embed Size (px)
Citation preview
CSc 120 Introduction to Computer Programming
II
Adapted from slides by Dr. Saumya Debray
14:StacksandQueues
Linear data structures Alineardatastructureisacollec6onofobjectswithastraight-lineorderingamongthem
‒ eachobjectinthecollec6onhasaposi*on‒ foreachobjectinthecollec6on,thereisano6onoftheobjectbeforeitora-erit
3
Data structures we've seen
Linear
• Pythonlists(akaarrays)• Linkedlists
Notlinear
• Dic6onaries• Sets
4
Today's topic
Linear
• Pythonlists(akaarrays)• Linkedlists• Stacks• Queues• Dequeues
Notlinear
• Dic6onaries• Sets
5
Keyproperty:thewayinwhichobjectsareaddedto,andremovedfrom,thecollec6on
Stacks Astackisalineardatastructurewhereobjectsareinsertedorremovedonlyatoneend
‒ allinser6onsanddele6onshappenatonepar6cularendofthedatastructure
‒ thisendiscalledthetopofthestack‒ theotherendiscalledthebo1omofthestack
7
inser6onsanddele6onshappenatoneend
Stacks: insertion of values Inser6onofasequenceofvaluesintoastack:
51733943
8
stackboRom
stacktop
None
None
Stacks: insertion of values Inser6onofasequenceofvaluesintoastack:
51733943
10
stackboRom
stacktop
517
Stacks: insertion of values Inser6onofasequenceofvaluesintoastack:
51733943
11
stackboRom
stacktop
51733
Stacks: insertion of values Inser6onofasequenceofvaluesintoastack:
51733943
12
stackboRom
stacktop
517339
Stacks: insertion of values Inser6onofasequenceofvaluesintoastack:
51733943
13
stackboRom
stacktop
51733943
Stacks: removal of values
15
stackboRom
stacktop
51733943
51733943Removingvaluesfromthestack:
orderinwhichvalueswereinserted
Stacks: removal of values
16
stackboRom
stacktop
51733
43
51733943Removingvaluesfromthestack:
43
orderinwhichvalueswereinserted
9
Stacks: removal of values
17
stackboRom
stacktop
517
43
51733943Removingvaluesfromthestack:
439
orderinwhichvalueswereinserted
933
Stacks: removal of values
18
stackboRom
stacktop
5
43
51733943Removingvaluesfromthestack:
43933
orderinwhichvalueswereinserted
93317
Stacks: removal of values
19
stackboRom
stacktop
43
51733943Removingvaluesfromthestack:
4393317
orderinwhichvalueswereinserted
933175
Stacks: removal of values
20
stackboRom
stacktop
5
43
51733943Removingvaluesfromthestack:
43933175
orderinwhichvalueswereinserted
93317
None
None
Stacks: removal of values
21
51733943Removingvaluesfromthestack:
43933175
orderinwhichvalueswereinserted
orderinwhichvalueswereremoved
Stacks: LIFO property
22
51733943Removingvaluesfromthestack:
43933175
orderinwhichvalueswereinserted
orderinwhichvalueswereremoved
valuesareremovedinreverseorderfromtheorderofinser6on
"LIFOorder"Lastin,Firstout
Methods for a Stack class • Stack():createsanewemptystack
• push(item):addsitemtothetopofthestack‒ returnsnothing‒ modifiesthestack
• pop():removesthetopitemfromthestack‒ returnstheremoveditem‒ modifiesthestack
• is_empty():checkswhetherthestackisempty‒ returnsaBoolean
23
Implementing a Stack class classStack:#thetopofthestackisthelastiteminthelistdef__init__(self):self._items=[]
defpush(self,item):self._items.append(item)
defpop(self):returnself._items.pop()
24
removesandreturnsthelastiteminalist
EXERCISE >>>s=Stack()>>>s.push(4)>>>s.push(17)>>>s.push(5)>>>x=s.pop()>>>y=s.pop()
25
←whatdoesthestackslooklikehere?whatarethevaluesofxandy?
EXERCISE >>>s=Stack()>>>s.push(4)>>>s.push(17)>>>s.push(5)>>>x=s.pop()>>>y=s.pop()>>>s.push(x)>>>s.push(y)
26
←whatdoesthestackslooklikehere?
An application: balancing parens
28
IDLE(thePythonshell)matchesupledandrightparens(),brackets[],andbraces{}
Howdoesitfigureouthowfarbacktohighlight?
An application: balancing parens Basicidea:Matcheach]withcorresponding[
‒ similarlyfor(…)and{…}pairs
‒ Idea:o maintainastacko onseeing'[':pusho onseeing']':popthematchingsymbolExample:[1,2,[3,[4],5,[7]]]
29
Stack (empty)
An application: balancing parens Basicidea:Matcheach]withcorresponding[
‒ similarlyfor(…)and{…}pairs
‒ Idea:o maintainastacko onseeing'[':pusho onseeing']':popthematchingsymbolExample:[1,2,[3,[4],5,[7]]]
30
[
Stack
âßtop
push
An application: balancing parens Basicidea:Matcheach]withcorresponding[
‒ similarlyfor(…)and{…}pairs
‒ Idea:o maintainastacko onseeing'[':pusho onseeing']':popthematchingsymbolExample:[1,2,[3,[4],5,[7]]]
31
[
[â
Stack
[
ßtop
ßtop
push
An application: balancing parens Basicidea:Matcheach]withcorresponding[
‒ similarlyfor(…)and{…}pairs
‒ Idea:o maintainastacko onseeing'[':pusho onseeing']':popthematchingsymbolExample:[1,2,[3,[4],5,[7]]]
32
[
[â
Stack
[
[
[
[
ßtop
ßtop
push
An application: balancing parens Basicidea:Matcheach]withcorresponding[
‒ similarlyfor(…)and{…}pairs
‒ Idea:o maintainastacko onseeing'[':pusho onseeing']':popthematchingsymbolExample:[1,2,[3,[4],5,[7]]]
33
[
[â
Stack
[
[
[
[
ßtop
matches:pop
An application: balancing parens Basicidea:Matcheach]withcorresponding[
‒ similarlyfor(…)and{…}pairs
‒ Idea:o maintainastacko onseeing'[':pusho onseeing']':popthematchingsymbolExample:[1,2,[3,[4],5,[7]]]
34
[
[â
Stack
[
[
[
[
ßtop
An application: balancing parens Basicidea:Matcheach]withcorresponding[
‒ similarlyfor(…)and{…}pairs
‒ Idea:o maintainastacko onseeing'[':pusho onseeing']':popthematchingsymbolExample:[1,2,[3,[4],5,[7]]]
35
[
[â
Stack
[
[
[
[
ßtop
ßtop
push
An application: balancing parens Basicidea:Matcheach]withcorresponding[
‒ similarlyfor(…)and{…}pairs
‒ Idea:o maintainastacko onseeing'[':pusho onseeing']':popthematchingsymbolExample:[1,2,[3,[4],5,[7]]]
36
[
[â
Stack
[
[
[
[
ßtop
ßtop
matches:pop
An application: balancing parens Basicidea:Matcheach]withcorresponding[
‒ similarlyfor(…)and{…}pairs
‒ Idea:o maintainastacko onseeing'[':pusho onseeing']':popthematchingsymbolExample:[1,2,[3,[4],5,[7]]]
37
[
[â
Stack
[
[
[
[
ßtop
An application: balancing parens Basicidea:Matcheach]withcorresponding[
‒ similarlyfor(…)and{…}pairs
‒ Idea:o maintainastacko onseeing'[':pusho onseeing']':popthematchingsymbolExample:[1,2,[3,[4],5,[7]]]
38
[
[
â
Stack
[
[
[
[
ßtop
matches:pop
An application: balancing parens Basicidea:Matcheach]withcorresponding[
‒ similarlyfor(…)and{…}pairs
‒ Idea:o maintainastacko onseeing'[':pusho onseeing']':popthematchingsymbolExample:[1,2,[3,[4],5,[7]]]
39
[
[
â
Stack
[
[
[
[ ßtop
An application: balancing parens Basicidea:Matcheach]withcorresponding[
‒ similarlyfor(…)and{…}pairs
‒ Idea:o maintainastacko onseeing'[':pusho onseeing']':popthematchingsymbolExample:[1,2,[3,[4],5,[7]]]
Elabora6on:Haveeachstackelementkeeptrackoftheposi6onofits[
40
[
[
Stack
[
[
[
[ ßtop
EXERCISE
41
Writeafunc*onbalanced(s) thatreturnsTrueifthestringsisbalancedwithrespectto‘[‘and’]’andFalseotherwise.
classStack:def__init__(self):self._items=[]
defpush(self,item):self._items.append(item)defpop(self):returnself._items.pop()defis_empty():returnself._items==[]
Related: Displaying web pages Webpage Displayconsidera5ons
43
mainheader:largefont,bold
secondaryheader:mediumfont,bold
italicsfont
boldfont
Ques5on:howdoesthewebbrowserfigureouthowmuchagivendisplayformatshouldinclude?E.g.,whichtextisinboldface,howmuchisinitalics,etc.
Related: Displaying web pages HTMLsource
47
"tags"
<h1>:"openheader1"</h1>:"closeheader1"<h2>:"openheader2"</h2>:"closeheader2"<i>:"openitalics"</i>:"closeitalics"
…
Related: Displaying web pages Webpage HTMLsource
48
Figuringouthowtodisplaydifferentpartsofthewebpagerequiresmatchingup“open-”and“close-”HTMLtags.Thisisessen6allythesameproblemasbalancingparens.
EXERCISE >>>s1=Stack()>>>s1.push(4)>>>s1.push(17)>>>s2=Stack()>>>s2.push(s1.pop())>>>s2.push(s1.pop())>>>s1.push(s2.pop())>>>s1.push(s2.pop())
49
←whatdoesthestacks1looklikehere?
Abstract Data Types Anabstractdatatype(ADT)describesasetofdatavaluesandassociatedopera6onsthatarespecifiedindependentofanypar6cularimplementa6on.AnADTisalogicaldescrip6onofhowweviewthedataandtheopera6onsallowedonthatdata.
o describeswhatthedatarepresentso nothowisthedatarepresented
Thedataisencapsulated.
51
Abstract Data Types Becausethedataisencapsulatedwecanchangetheunderlyingimplementa6onwithoutaffec6ngthewaytheADTbehaves.
o thelogicaldescrip6onremainsthesameo theopera6onsremainthesame
52
EXERCISE
53
Hypothe*cal:Python7hasjustbeenreleasedandbuilt-inlistsareinefficient.Infact,allopera*onsareO(n2).Avoidtheseinefficienciesbyimplemen*ngtheStackclassusingLinkedLists.
A Queue ADT Aqueueisalineardatastructurewhereinser6onsanddele6onshappenatdifferentends
‒ inser6onshappenatoneend(thequeue's"back“,or“tail”)
‒ dele6onshappenattheotherend(thequeue's"front“,or“head”)
55
dele6onsoccuratthisend(head)
inser6onsoccuratthisend
(tail)
Queues: insertion of values Inser6onofasequenceofvaluesintoaqueue:
56
NoneNonequeueback
queuefront
51733943
Queues: insertion of values
57
queueback
queuefront
5
Inser6onofasequenceofvaluesintoaqueue: 51733943
Queues: insertion of values
58
queueback
queuefront
17 5
Inser6onofasequenceofvaluesintoaqueue: 51733943
Queues: insertion of values
59
queueback
queuefront
33 17 5
Inser6onofasequenceofvaluesintoaqueue: 51733943
Queues: insertion of values
60
queueback
queuefront
9 33 17 5
Inser6onofasequenceofvaluesintoaqueue: 51733943
Queues: insertion of values
61
queueback
queuefront
43 9 33 17 5
Inser6onofasequenceofvaluesintoaqueue: 51733943
51733943
Queues: removal of values
63
queueback
queuefront
43 9 33 17 5
orderofinser*on
Removingvaluesfromthisqueue:
51733943
Queues: removal of values
64
queueback
queuefront
43 9 33 5
orderofinser*on
Removingvaluesfromthisqueue: 5
17
51733943
Queues: removal of values
65
queueback
queuefront
43 9 17 5
orderofinser*on
Removingvaluesfromthisqueue: 517
33
51733943
Queues: removal of values
66
queueback
queuefront
43 33 17 5
orderofinser*on
Removingvaluesfromthisqueue: 51733
9
51733943
Queues: removal of values
67
queueback
queuefront
9 33 17 5
orderofinser*on
Removingvaluesfromthisqueue: 517339
43
51733943
Queues: removal of values
68
queueback
queuefront
43 9 33 17 5
orderofinser*on
Removingvaluesfromthisqueue: 51733943
NoneNone
51733943
Queues: FIFO property
70
orderofinser*on
51733943orderofremoval
valuesareremovedinorderinwhichtheyareinserted
"FIFOorder"Firstin,Firstout
Methods for a queue class • Queue():createsanewemptyqueue• enqueue(item):addsitemtothebackofthequeue
‒ modifiesthequeue‒ returnsnothing
• dequeue():removesandreturnstheitematthefrontofthequeue‒ returnstheremoveditem‒ modifiesthequeue
• is_empty():checkswhetherthequeueisempty‒ returnsaBoolean
• size():returnsthesizeofthequeue‒ returnsaninteger
71
Implementing a queue class • Useabuilt-inlistfortheinternalrepresenta6on
‒ Pythonlistscanbeaddedattothefrontorattheend• Firstimplementa6on:
‒ theheadisthe0thelement‒ thetailisthenthelement
• Secondimplementa6on‒ theheadisthenthelement‒ thetailisthe0thelement
72
Implementing a Queue class I classQueue:#thefrontofthequeueisthefirstiteminthelistdef__init__(self):self._items=[]
defenqueue(self,item):self._items.append(item)
defdequeue(self):returnself._items.pop(0)
73
removesandreturnsitem0fromthelist
0 1 2 3 4 5
�
head
�
tail
Implementing a Queue class II classQueue:#thefrontofthequeueisthelastiteminthelistdef__init__(self):self._items=[]
defenqueue(self,item):self._items.insert(0,item)
defdequeue(self):returnself._items.pop()
74
removesandreturnsthelastiteminthelist
0 1 2 3 4 5�
tail
�
head
EXERCISE >>>q=Queue()>>>q.enqueue(4)>>>q.enqueue(17)>>>x=q.dequeue()>>>q.enqueue(5)>>>y=q.dequeue()
75
←whatarethevaluesofxandy?
EXERCISE >>>q=Queue()>>>q.enqueue(4)>>>q.enqueue(17)>>>x=q.dequeue()>>>y=q.dequeue()>>>q.enqueue(y)>>>q.enqueue(x)>>>q.enqueue(y)
76
←whatdoesthequeueqlooklikehere?
Application 1: Simulation • Typicalapplica6onssimulateproblemsthatrequiredatatobemanagedinaFIFOmanner‒ Hotpotato
o Kidsstandinacircleandpassa“hotpotato”aroundun6ltoldtostop.Thepersonholdingthepotatoistakenoutofthecircle.Theprocessisrepeatedun6lonlyonepersonremains.
‒ Generalized:Givennelements,eliminateeverykthelementrepeatedlyun6lonly1elementisled.Whatwastheoriginalposi6onoftheremainingelement?
• Useasimula*ontodeterminewhichelementremains.
78
EXERCISE Problem:Givennelements,eliminateeverykthelementrepeatedlyun6lonly1elementisled.Whatwastheoriginalposi6onoftheremainingelement?useaqueuetosimulatethecirclenisthenumberofelementstoputintothequeuewhilethereismorethanoneelementinthequeueeliminateeverykthelement
Whatopera6onstakeanelementfromthefrontofthequeueandplaceitatthebackofthequeue?
79
General solution for k=2 • Givennelements,eliminateeverykthelementrepeatedlyun6lonly1elementisled.Whatwastheoriginalposi6onoftheremainingelement?
• Whenk=2,theoriginalposi6oncanbederivedfromthebinaryrepresenta6onofn.
Takethefirstdigitofthebinaryrepresenta6on.MoveittotheendTheresultistheoriginalposi6on.Ex:n=41,k=2Inbinaryn=101001Therefore,theoriginalposi6on(inbinary)is010011and010011=24+21+20=19hRps://en.wikipedia.org/wiki/Josephus_problem#CITEREFDowdyMays1989
80
Application 2 : Simulation • Supposeweareopeningagrocerystore.Howmanycheckoutlinesshouldweputin?‒ toofew⇒longwait6mes,unhappycustomers‒ toomany⇒wastedmoney,space
• Usesimula*onsofthecheckoutprocesstoguidethedecision‒ studyexis6ngstorestofigureouttypicalshoppingandcheckout6mes
‒ es6mateno.ofcustomersexpectedatthenewloca6on‒ runsimula6onstodeterminecustomerwait6meandcheckoutlineu6liza6onunderdifferentscenarios
81
Discrete event simulation
82
…
queue
…
arrivalsdepartures
arrivalratedistribu6on
departureratedistribu6on
servers
customersByvaryingtheparametersofthesimula6on(arrivalanddeparturerates,no.ofservers)wecantryoutdifferentscenarios
Summary • Stacksandqueuesareabstractdatatypes(ADTs)
‒ similarinthattheyarebothlineardatastructures‒ itemscanbethoughtofasarrangedinaline‒ eachitemhasaposi6onandabefore/aderrela6onshipwiththeotheritems
• Theydifferinthewayitemsareaddedandremoved‒ stacks:itemsaddedandremovedatoneend
o resultsinLIFObehavior‒ queues:itemsaddedatoneend,removedattheother
o resultsinFIFObehavior
• Theyfindawiderangeofapplica6onsincomputerscience
83