Stack Push Down Stack KMITL 01076249 Data Structures

  • Slides: 39
Download presentation
Stack (Push Down Stack) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data

Stack (Push Down Stack) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Stack 1

Stack pop push Top of the stack LIFO Last in First out Pick ONE

Stack pop push Top of the stack LIFO Last in First out Pick ONE ? Which one ? Insert ONE ? Where? http: //www. clipartpanda. com รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Stack 2

Stack http: //clipart-library. com/search/ รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data

Stack http: //clipart-library. com/search/ รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Stack 3

Stack Applications 1. Parenthesis Matching 2. Evaluate Postfix Expression 3. Infix to Postfix Conversion

Stack Applications 1. Parenthesis Matching 2. Evaluate Postfix Expression 3. Infix to Postfix Conversion (Reverse Polish Notation) 4. Function Call (clearly see in recursion) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Stack 4

Parenthesis Matching ( a+b-c *[d+e]/{f*(g+h) } Match ? Algorithm ? รศ. ดร. บญธร เครอตราช

Parenthesis Matching ( a+b-c *[d+e]/{f*(g+h) } Match ? Algorithm ? รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Stack 5

Parenthesis Matching [ ( a+b-c }*[d+e]/{f*(g+h) } Match ? Algorithm ? รศ. ดร. บญธร

Parenthesis Matching [ ( a+b-c }*[d+e]/{f*(g+h) } Match ? Algorithm ? รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Stack 6

Parenthesis Matching 45 ( 3 + 2 ) / { 4**5 } Match ?

Parenthesis Matching 45 ( 3 + 2 ) / { 4**5 } Match ? Algorithm ? รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Stack 7

Parenthesis Matching random / / / (d+e)-3}] / / // /[ (a+b)*{ ↑ ↑

Parenthesis Matching random / / / (d+e)-3}] / / // /[ (a+b)*{ ↑ ↑ 1. 2. 3. 4. 5. 6. 7. 8. รศ. ดร. บญธร 1. Simulate ���� • Data Structure : Python List • Expensive 2. Use Stack Repeat random position (until check all paren || not match). Scan out both ways. if Left side = open paren & Right side = close paren. if match : Check out. goto 2 else end process : Not match. else goto 1 เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Stack 8

Logical Abstract Data Type Logical ADT : 1. Data : ของมลำดบ มปลายบน 2. Methods

Logical Abstract Data Type Logical ADT : 1. Data : ของมลำดบ มปลายบน 2. Methods : pop 1. init() init empty stack 2. push(i) insert i ท 3. i = pop() return + เอาของท 4. i = peek() return ของท top )ไมเอาออก ( 5. b = is. Empty() stack empty ? 6. b = is. Full() 7. i = size() เครอตราช รศ. ดร. บญธร push Top top ออก top LIFO Last in First out stack full ? return จำนวนของใน stack. Data Structures & Algorithms : Stack KMITL 01076249 รศ. กฤตวน ศรบรณ 10

Stack Implementation Data Implementation ? Logical ADT : 1. Data : ของมลำดบ มปลายบนPython List

Stack Implementation Data Implementation ? Logical ADT : 1. Data : ของมลำดบ มปลายบนPython List 2. Methods : 1. init() init empty stack 2. push(i) insert i ท 4. i = peek() S == [] ? 5. b = is. Empty() stack empty ? 7. i = size() เครอตราช Top top )ไมเอาออก ( รศ. ดร. บญธร S = [] push S. append(i) return + เอาของท ใสทาย top ออก i = S. pop() อนทาย i = S[-1] return ของท top 3. i = pop() 6. b = is. Full() pop stack full ? Python List expands size automatically i = len(S) LIFO Last in First out return จำนวนของใน stack. Data Structures & Algorithms : Stack KMITL 01076249 รศ. กฤตวน ศรบรณ 11

Stack Data Implementation 1. Data : __init__() : constructor ������� 2 underscores รศ. ดร.

Stack Data Implementation 1. Data : __init__() : constructor ������� 2 underscores รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 2 underscores 01076249 Data Structures & Algorithms : Stack 12

self คอ object ทเรยก method Data Implementation : __init__() ในแตละครง เชน s ������ =

self คอ object ทเรยก method Data Implementation : __init__() ในแตละครง เชน s ������ = 1. Data Implementation : Stack ������� -> Python Stack() List ทำใน constructor self หมายถง s เสมอนเรยก s = Stack(s) __init__() self จะถก pass เปน arg. ตวแรก โดยอตโนมต docstring : ใน triple quote print(Stack. __doc__) class Stack: """ class Stack create empty stack """ docstring constructor def __init__(self): function self. items = [] ถก เรยกโดยอตโนม ตเมอ instantiate instance (object) ใหม โดยไม instance pass argument s = Stack() print(s. items) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL [] 01076249 Data Structures & Algorithms : Stack constructor : ใช define Instance Attributes ได ในตวอยางนม attribute เดยวคอ items : Instance Attributes สำหรบแตละ instance 13

Default Argument class Stack: """ class Stack default : empty stack / Stack([list]) """

Default Argument class Stack: """ class Stack default : empty stack / Stack([list]) """ def __init__(self, list = None): if list == None: self. items = [] else: self. items = list default argument ถาไมมการ pass arg. มา list = None ถา pass arg. มา list = ตวท pass มา Object None ใชเชค obj identity s = Stack() [] print(s. items) s 1 = Stack(['A', 'B', 'C']) ['A', 'B', 'C'] print(s 1. items) ไมเหมอนกบ หลายตวได รศ. ดร. บญธร C++ & Java ใน Python ไมสามารถม เครอตราช รศ. กฤตวน ศรบรณ KMITL constructor 01076249 Data Structures & Algorithms : Stack 14

Default Argument default value จะถก evlauated ครงเดยว ณ function definition ใน scope ท define

Default Argument default value จะถก evlauated ครงเดยว ณ function definition ใน scope ท define i=5 7 def f( arg = i+2): print(arg) 0 arg = 0 print(arg) print('----') i=6 f() เมอมการ call fn formal arg. จะถก bind กบ default value นน output arg 7 0 -------3 0 -------7 0 ---- f(3) f() รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 2

default value จะถก evlauated ครงเดยว ณ function definition ใน scope ท define def f(

default value จะถก evlauated ครงเดยว ณ function definition ใน scope ท define def f( L = []): Default Argument 2 ตอง ระวง เมอ default arg. เปน mutable type output def f(L = None): if L is None: L = [] print(L) L. append(1) def f(x, L = None): if L is None: L = [] L. append(x) output return(L) f() [] f() [1] f() [] f([2]) [2] f() [1, 1] f() [] print(L) L. append(1) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ output [1] print(f(1)) print(f(2)) print(f(7, [5, 6])) print(f(3)) [2] [5, 6, 7] [3] KMITL 01076249 Data Structures & Algorithms : Tree 2

push() class Stack: def __init__(self, list = None): if list == None: self. items

push() class Stack: def __init__(self, list = None): if list == None: self. items = [] else: self. items = list def push(self, i): self. items. append(i) Check Stack Overflow ? -> No Python list automatically expanding size append : insert I ททาย list s = Stack() print(s. items) [] C s. push('A') print(s. items) ['A'] A s. push('B') print(s. items) B ['A', 'B'] s. push('C') print(s. items) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ ['A', 'B', 'C' ] KMITL 01076249 Data Structures & Algorithms : Stack 18

pop() �� class Stack: def pop(self): # remove & return ���� pop : delete

pop() �� class Stack: def pop(self): # remove & return ���� pop : delete last element of the list return self. items. pop() อยาลม return !!! print(s. items) ['A', 'B'] print(s. pop()) B print(s. items) ['A'] print(s. pop()) A print(s. items) [] s. pop() # error Stack Underflow รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL B A 01076249 Data Structures & Algorithms : Stack 19

peek() �� class Stack: def peek(self): # return ���� return self. items[ -1] print(s.

peek() �� class Stack: def peek(self): # return ���� return self. items[ -1] print(s. items) ['A', 'B'] print(s. peek()) print(s. items) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ B B A ['A', 'B'] KMITL 01076249 Data Structures & Algorithms : Stack 20

is. Empty() �� class Stack: def is. Empty(self): return self. items == [] print(s.

is. Empty() �� class Stack: def is. Empty(self): return self. items == [] print(s. items) ['A', 'B'] B print(s. is. Empty()) false A รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Stack 21

size() �� class Stack: def size(self): return len(self. items) print(s. items) ['A', 'B'] print(s.

size() �� class Stack: def size(self): return len(self. items) print(s. items) ['A', 'B'] print(s. size()) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ 2 KMITL B A 01076249 Data Structures & Algorithms : Stack 22

Stack Implementation class Stack: """ class Stack default : empty stack / Stack([. .

Stack Implementation class Stack: """ class Stack default : empty stack / Stack([. . . ]) """ def __init__(self, list = None): if list == None: self. items = [] else: self. items = list def push(self, i): self. items. append(i) def pop(self): return self. items. pop() def peek(self): return self. items[-1] def __str__(self): s = 'stack of '+ str(self. size())+' items : ' for ele in self. items: s += str(ele)+' ' __str__() ตอง return str return s def is. Empty(self): return self. items == [] def size(self): return len(self. items) s 1 = Stack([1, 2, 3]) print(s 1. items) [1, 2, 3] print(s 1) stack of 3 items : 1 2 3 รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Stack 23

Writing Code Def paren. Match(s) : # your code ? รศ. ดร. บญธร เครอตราช

Writing Code Def paren. Match(s) : # your code ? รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Stack 24

Design Tools, Warnier-Orr Diagram Code : difficult Pseudocode : easier if open. Paren(c) :

Design Tools, Warnier-Orr Diagram Code : difficult Pseudocode : easier if open. Paren(c) : s. push(c) elif close. Paren(c) : ch = s. pop() match = is. Match(c, ch) Warnier – Orr Diagram : easier if (c is an open parenthesis) push c to stack s else if (c is an close parenthesis) pop ch from stack s if (ch matches c) match = true else match = false c == open paren s. push(c) Warnier – Orr Diagram + or + ch = s. pop() c == close paren pop&check match = is. Match(ch, c) if … then not A รศ. ดร. บญธร A เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Stack 25

Warnier-Orr Diagram Design Tool [ (a+b)*{ (d+e)-3}] Init empty stack s error=false read ch

Warnier-Orr Diagram Design Tool [ (a+b)*{ (d+e)-3}] Init empty stack s error=false read ch ch = non_paren Scan (not EOF && not error) ch = open paren + s. push(ch) s. empty() ch = close paren + s. empty() Paren matching error =true(no-open-paren ) open = s. pop() match(open, ch) error = true match(open, ch ) error + MATCH s. empty() error ( + MISSMATCH open paren exceed s. empty() รศ. ดร. บญธร เครอตราช (missmatch) no open-paren / missmatch รศ. กฤตวน ศรบรณ KMITL [ 01076249 Data Structures & Algorithms : Stack 26

Python : Parenthesis Matching def paren. Matching(str): s = Stack() i=0 # index :

Python : Parenthesis Matching def paren. Matching(str): s = Stack() i=0 # index : str[i] error = 0 while i < len(str) and error == 0 : c = str[i] if c in '{[(': s. push(c) else: if c in '}])': if s. size() > 0: if not match(s. pop(), c): error = 1 # open & close not match else: # empty stack error = 2 # no open paren i += 1 if s. size() > 0: error = 3 return error, c, i, s รศ. ดร. บญธร เครอตราช # stack not empty # open paren(s) excesses รศ. กฤตวน ศรบรณ KMITL str = '[{a+b-c}' err, c, i, s = paren. Matching(str) if err == 1: print(str , 'unmatch open-close ') elif err == 2: print(str , 'close paren excess') elif err == 3: print(str , 'open paren(s) excess ', s. size(), ': ', end='' ) for ele in s. item: print(ele, sep=' ', end = '') print() else: print(str, 'MATCH') def match(open, close): return (open == '(' and close == ')') or (open == '{' and close == '}') or (open == '[' and close == ']') def match 2(op, cl): opens = "([{" closes = ")]}" return opens. index(op) == closes. index(cl) 01076249 Data Structures & Algorithms : Stack 27

Stack Application 1. Parenthesis Matching 2. Evaluate Postfix Expression 3. Infix to Postfix Conversion

Stack Application 1. Parenthesis Matching 2. Evaluate Postfix Expression 3. Infix to Postfix Conversion (Reverse Polish Notation) 4. Function Call (clearly see in recursion) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Stack 28

Postfix Notation (Polish Notation) Infix Form Prefix Form Postfix Form a+b +ab ab+ a+b*c

Postfix Notation (Polish Notation) Infix Form Prefix Form Postfix Form a+b +ab ab+ a+b*c +a*bc abc*+ รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Stack 29

Evaluate Postfix Notation มธรรมชาตเปน ตวกอนหนามน stack: operator เปนของ operands 2 6523+8*-3+* =? 3 2

Evaluate Postfix Notation มธรรมชาตเปน ตวกอนหนามน stack: operator เปนของ operands 2 6523+8*-3+* =? 3 2 input: 6523 Push : 6, 5, 2, 3 5 6 S รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL input: + o 2 <- pop#1 o 1 <- pop#2 push + 5 What ‘s next ? 01076249 Data Structures & Algorithms : Stack 5 5 6 S 30

6523+8*-3+* =? input: 6523 input: + Push : 6 5 2 3 3 pop#1

6523+8*-3+* =? input: 6523 input: + Push : 6 5 2 3 3 pop#1 → 3 2 pop#2 → 2 5 5 push 2+3 5 6 6 s input: 8 s 8 input: * push 5 pop#1 → 8 40 5 pop#2 → 5 5 6 push 5*8 6 8 input: - input: 3 pop#1 → 40 push 3 3 pop#2 → 5 -35 push 5 -40 6 6 input: + input: * pop#1 → 3 pop#1 → -32 pop#2 → -35 push รศ. ดร. บญธร -35+3 เครอตราช pop#2 → 6 -32 6 รศ. กฤตวน ศรบรณ push 6 * -32 KMITL 01076249 Data Structures & Algorithms : Stack - 192 31

Stack Application 1. Parenthesis Matching 2. Evaluate Postfix Expression 3. Infix to Postfix Conversion

Stack Application 1. Parenthesis Matching 2. Evaluate Postfix Expression 3. Infix to Postfix Conversion (Reverse Polish Notation) 4. Function Call (clearly see in recursion) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Stack 32

Infix to Postfix Conversion aa*b+c ab*c+ ===> Notice : output: operands’ order is the

Infix to Postfix Conversion aa*b+c ab*c+ ===> Notice : output: operands’ order is the same as input’s. output stack รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Stack 33

Infix to Postfix Conversion a*b+c input: a*b+c a*b+c รศ. ดร. บญธร เครอตราช ---- >

Infix to Postfix Conversion a*b+c input: a*b+c a*b+c รศ. ดร. บญธร เครอตราช ---- > stack: * * + + รศ. กฤตวน ศรบรณ KMITL ab*c+ output: a a ab ab*c+ 01076249 Data Structures & Algorithms : Stack 34

Infix to Postfix Conversion a+b*c input: a+b*c output: a a ab + + *

Infix to Postfix Conversion a+b*c input: a+b*c output: a a ab + + * + a+b*c รศ. ดร. บญธร stack: เครอตราช รศ. กฤตวน ศรบรณ abc*+ ---- > ab abc*+ KMITL 01076249 Data Structures & Algorithms : Stack 35

Infix to Postfix Conversion input: a+b*c-d a+b*c-d รศ. ดร. บญธร เครอตราช stack: output: abc*+d-

Infix to Postfix Conversion input: a+b*c-d a+b*c-d รศ. ดร. บญธร เครอตราช stack: output: abc*+d- a a ab + + * + - รศ. กฤตวน ศรบรณ a+b*c-d => ab abc*+d- KMITL 01076249 Data Structures & Algorithms : Stack 36

Infix to Postfix Conversion abc*+de/f+g*- a+b*c-(d/e+f)*g => a+b*c-(d/e+f)*g a+b*c-(d/e+f)*g รศ. ดร. บญธร เครอตราช รศ.

Infix to Postfix Conversion abc*+de/f+g*- a+b*c-(d/e+f)*g => a+b*c-(d/e+f)*g a+b*c-(d/e+f)*g รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ + * + ( / ( - KMITL ab abc*+de 01076249 Data Structures & Algorithms : Stack 37

Infix to Postfix Conversion (cont. ) a+b*c-(d/e+f)*g => a+b*c-(d/e+f)*g a+b*c-(d/e+f)*g รศ. ดร. บญธร เครอตราช

Infix to Postfix Conversion (cont. ) a+b*c-(d/e+f)*g => a+b*c-(d/e+f)*g a+b*c-(d/e+f)*g รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ / ( + ( * - KMITL abc*+de/f+g*abc*+de/f+ abc*+de/f+g*- 01076249 Data Structures & Algorithms : Stack 38

Stack Application 1. Parenthesis Matching 2. Evaluate Postfix Expression 3. Infix to Postfix Conversion

Stack Application 1. Parenthesis Matching 2. Evaluate Postfix Expression 3. Infix to Postfix Conversion (Reverse Polish Notation) 4. Function Call (clearly see in recursion) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Stack 39