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

Data Structures & Algorithms In this course, Data Structures & Algorithms : 1. Data

Data Structures & Algorithms In this course, Data Structures & Algorithms : 1. Data Structures abstract data types : stack, queue, linked list, trees, heap, graph. 2. Algorithms : recursion, complexity (algorithm analysis) , hashing, searching, sorting. รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 22

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

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

Stack : ����������� ordered collection of items ��������� top ��� stack ����� (push) ���

Stack : ����������� ordered collection of items ��������� top ��� stack ����� (push) ��� (pop) ��� top ��� stack pop push Top of the stack LIFO Last in First out ������������� pop ������ ? ���� top http: //www. clipartpanda. com รศ. ดร. บญธร เครอตราช ��� push รศ. กฤตวน ศรบรณ ����� top �? KMITL 01076249 Data Structures & Algorithms : Tree 24

Queue แถวคอย ? http: //www. gograph. com/vector-clip-art/queue. html รศ. ดร. บญธร เครอตราช รศ. กฤตวน

Queue แถวคอย ? http: //www. gograph. com/vector-clip-art/queue. html รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 25

Queue แถวคอย Queue : ����������� ordered collection of items ���������� rear/tail �������� FIFO List

Queue แถวคอย Queue : ����������� ordered collection of items ���������� rear/tail �������� FIFO List (en. Queue) First. In. First. Out ���������� front/head �������� (de. Queue) front head de. Queue (delete) รศ. ดร. บญธร เครอตราช rear tail Next ! Oh my turn Who ? รศ. กฤตวน ศรบรณ en. Queue (insert) KMITL I need some ! Where should I go ? 01076249 Data Structures & Algorithms : Tree 26

list List : ordered collection of items ����� list Superset ���������� (insert) ����� (delete)

list List : ordered collection of items ����� list Superset ���������� (insert) ����� (delete) ����� insert / delete รศ. ดร. บญธร เครอตราช To Buy : 1. Bread 2. Milk 3. Eggs 4. Fruit 5. Rice 6. Pasta 7. Butter 8. Juice รศ. กฤตวน ศรบรณ of Stack & Queue head tail KMITL 01076249 Data Structures & Algorithms : Tree 27

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 : Tree 28

Parenthesis Matching ( a+b-c *[d+e]/{f*(g+h) } ( a+b-c }*[d+e]/{f*(g+h) } ( a+b-c )*[d+e] }

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

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

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

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

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

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

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

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

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

Mutable Type Default Argument Default argument : ให = คาน เมอไมมการ pass คามา def

Mutable Type Default Argument Default argument : ให = คาน เมอไมมการ pass คามา def f( L = [] ): คา default จะถกสรางขน ครงเดยว ณ function definition ใน scope ท define functon ตอง ระวง เมอ เปน mutable type def f(L = None): ��� f() ���� constructor ��� stack if L is None: ��� init empty stack ����������� print(L) L = [] else : pass L. append(1) output L. append(1) f() [] f() [1] f() f([2]) [2] f() [1, 1] default L L รศ. ดร. บญธร L [1, 1, 1 ] default L [2, 1 ] เครอตราช รศ. กฤตวน ศรบรณ None L [ 1] KMITL 01076249 Data Structures & Algorithms : Tree 215

__init__() with Default Argument class Stack: """ class Stack default : empty stack /

__init__() with 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 มา s = Stack() s 1 = Stack(['A', 'B', 'C']) ไมเหมอนกบ ไดตวเดยว รศ. ดร. บญธร เครอตราช C++ & Java รศ. กฤตวน ศรบรณ ใน Python ม constructor KMITL 01076249 Data Structures & Algorithms : Tree 216

Stack Operation Implementation 1. Data : __init__() : constructor ������� 2. Methods (Operations) :

Stack Operation Implementation 1. Data : __init__() : constructor ������� 2. Methods (Operations) : . 2 push() : ������ top. 3 pop () : ������ top. 4 peek() : ��top �����. 5 is. Empty() : stack ���� ? . 6 size() : ������ รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 217

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 self. size = len(self. items) Check Stack Overflow ? -> No Python list automatically expanding size def push(self, i): list. append (i): insert i ������� list self. items. append(i) self. size += 1 s. items s = Stack() [] s. push('A') ['A'] s. push('B') ['A', 'B'] s. push('C') ['A', 'B', 'C' ] รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ C B KMITL A 01076249 Data Structures & Algorithms : Tree 218

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

pop() class Stack: def __init__(self, list = None): if list == None: self. items = [] else: self. items = list # remove & return ���� def pop(self): return self. items. pop() อยาลม list. pop() : delete ������� list return !!! list. pop(i) : delete ������ index i ��� list print(s. items) ['A', 'B'] print(s. pop()) B print(s. pop()) A s. pop() รศ. ดร. บญธร B # error Stack Underflow เครอตราช รศ. กฤตวน ศรบรณ KMITL A 01076249 Data Structures & Algorithms : Tree 219

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

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

is. Empty() class Stack: def __init__(self, list = None): if list == None: self.

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

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

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

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)+' ' return s __str__() ตอง def is. Empty(self): return self. items == [] def size(self): return len(self. items) return string 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 : Tree 223

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

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

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) 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 Warnier – Orr Diagram or + Warnier – Orr Diagram : easier s. push(c) + c == close paren ch = s. pop() pop&check match = is. Match(ch, c) if … then not A รศ. ดร. บญธร A เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 225

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 ch = open paren (not EOF + && s. push(ch) s. empty() not error) ch = close paren Paren matching error =true(no-open-paren) + open = s. pop() s. empty() match(open, ch) error = true match(open, ch) error + s. empty() MATCH ( + error s. empty() รศ. ดร. บญธร (missmatch) no open-paren / missmatch เครอตราช รศ. กฤตวน ศรบรณ MISSMATCH open paren exceed KMITL [ 01076249 Data Structures & Algorithms : Tree 226

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 เครอตราช รศ. กฤตวน ศรบรณ 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) KMITL 01076249 Data Structures & Algorithms : Tree 227

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 : Tree 228

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 : Tree 229

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 input: + o 2 <- pop#1 5 o 1 <- pop#2 + 5 push 5 6 S What ‘s next ? รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 230

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 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 s 3 pop#2 → 5 -35 push 5 -40 6 6 input: + input: * pop#1 → 3 pop#1 → -32 pop#2 → -35 push -32 -35+3 รศ. ดร. บญธร เครอตราช 6 รศ. กฤตวน ศรบรณ pop#2 → 6 push 6 * -32 KMITL - 192 01076249 Data Structures & Algorithms : Tree 231

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 : Tree 232

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 : Tree 233

Infix to Postfix Conversion a*b+c input: stack: a*b+c a*b+c รศ. ดร. บญธร ab*c+ ----

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

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

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

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

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

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

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 รศ. ดร. บญธร เครอตราช / ( + ( * - abc*+de/f+g*abc*+de/f+ abc*+de/f+g*- รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Tree 238

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 : Tree 239