COMPSCI 105 SS 2015 Principles of Computer Science 09 ADT & Stacks.

Slides:



Advertisements
Similar presentations
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Advertisements

Stacks Chapter 11.
Stacks Chapter 21 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
COSC 2006 Chapter 7 Stacks III
COMPSCI 105 S Principles of Computer Science 12 Abstract Data Type.
COMPSCI 105 S Principles of Computer Science 13 Stacks.
COMPSCI 105 SS 2015 Principles of Computer Science Queues.
Lecture 12 – ADTs and Stacks.  Modularity  Divide the program into smaller parts  Advantages  Keeps the complexity managable  Isolates errors (parts.
Stacks Chapter 5. Chapter Objectives  To learn about the stack data type and how to use its four methods: push, pop, peek, and empty  To understand.
Chapter 3 Stacks.
Topic 15 Implementing and Using Stacks
Stacks Chapter 5. Chapter 5: Stacks2 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop, peek, and empty.
© 2006 Pearson Addison-Wesley. All rights reserved7A-1 Chapter 7 Stacks.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Stacks Chapter Chapter Contents Specifications of the ADT Stack Using a Stack to Process Algebraic Expressions Checking for Balanced Parentheses,
CHAPTER 6 Stacks. 2 A stack is a linear collection whose elements are added and removed from one end The last element to be put on the stack is the first.
Chapter 6 Stacks. © 2005 Pearson Addison-Wesley. All rights reserved6-2 The Abstract Data Type Specifications of an abstract data type for a particular.
TCSS 342, Winter 2005 Lecture Notes
Topic 15 Implementing and Using Stacks
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Stacks.
Stacks Chapter 6 Data Structures and Problem Solving with C++: Walls and Mirrors, Frank Carrano, © 2012.
CSE 143 Lecture 7 Stacks and Queues reading: "Appendix Q" (see course website) slides created by Marty Stepp and Hélène Martin
Exam 1 –Monday June 25 th –open Book / Open Notes –No Electronic Devices (calculators, laptops, etc) –Room Number: W –Time: 5:30pm to 8:00pm.
© 2006 Pearson Addison-Wesley. All rights reserved7A-1 Chapter 7 Stacks (and a bit of generics for flavor)
Fundamentals of Python: From First Programs Through Data Structures Chapter 14 Linear Collections: Stacks.
Comp 245 Data Structures Stacks. What is a Stack? A LIFO (last in, first out) structure Access (storage or retrieval) may only take place at the TOP NO.
Chapter 6 Stacks CS Data Structures Mehmet H Gunes Modified from authors’ slides.
1 Stacks – Chapter 3 A stack is a data structure in which all insertions and deletions of entries are made at one end, called the top of the stack. Alternatively,
Stack and Queue.
CSC 205 Programming II Postfix Expressions. Recap: Stack Stack features Orderly linear structure Access from one side only – top item Stack operations.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
CSE 143 Lecture 5 Stacks and Queues slides created by Marty Stepp
Computer Science Department Data Structure & Algorithms Problem Solving with Stack.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
Chapter 7 Stacks. © 2004 Pearson Addison-Wesley. All rights reserved 7-2 The Abstract Data Type: Developing an ADT During the Design of a Solution Specifications.
Stacks  Introduction  Applications  Implementations  Complex Applications.
CSE 373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks; Eclipse.
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
Chapter 6 B Stacks. © 2004 Pearson Addison-Wesley. All rights reserved6 B-2 Comparing Implementations All of the three implementations are ultimately.
CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in Office.
CHP-3 STACKS.
Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving data LIFO (Last In First Out) structure.
CSE 373 Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks; Eclipse.
Stack – Data Structure. Stack Definition class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item):
CC 215 DATA STRUCTURES MORE ABOUT STACK APPLICATIONS Dr. Manal Helal - Fall 2014 Lecture 6 AASTMT Engineering and Technology College 1.
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
Lecture - 6(Stacks) On Data structures. Prepared by, Jesmin Akhter, Lecturer, IIT,JU Lecture Outline What is a Stack? Array implementation of stacks Operations.
Stacks Access is allowed only at one point of the structure, normally termed the top of the stack access to the most recently added item only Operations.
CS Data Structures Chapter 6 Stacks Mehmet H Gunes
Stacks Chapter 5.
Stacks Chapter 6.
Revised based on textbook author’s notes.
COMPSCI 107 Computer Science Fundamentals
Stack A stack is a linear, homogeneous, container that stores and dispenses its content in a LIFO manner. LIFO - The last (most recent) item inserted,
COMPSCI 107 Computer Science Fundamentals
CSE 373: Data Structures and Algorithms
Copyright ©2012 by Pearson Education, Inc. All rights reserved
STACK CHAPTER 03 Developed By :- Misha Ann Alexander Data Structures.
Visit for more Learning Resources
Building Java Programs Chapter 14
COMPUTER 2430 Object Oriented Programming and Data Structures I
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Stacks Chapter 6 Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
COMPUTER 2430 Object Oriented Programming and Data Structures I
Topic 15 Implementing and Using Stacks
Stacks Chapter 5.
Stack.
Data Structures and Algorithms 2/2561
Chapter 7 (continued) © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

COMPSCI 105 SS 2015 Principles of Computer Science 09 ADT & Stacks

Agenda & Reading  Agenda  Abstract Data Type (ADT)  The Stack Abstract Data Type (ADT)  Two Implementations  Example Applications  Checking for Balanced Braces  Bracket Matching  Postfix Calculation  Conversion from Infix to Postfix  Reading  Textbook: Problem Solving with Algorithms and Data Structures  Chapter 1: Introduction  Chapter 3: Basic Data Structures Lecture 09-10COMPSCI1052

1 Data abstraction Modularity  Modularity (divide a program into manageable parts)  Keeps the complexity of a large program manageable  Isolates errors  Eliminates redundancies  Encourages reuse (write libraries)  A modular program is  Easier to write / Easier to read / Easier to modify Lecture 09-10COMPSCI1053

1 Data abstraction Information hiding  Hides certain implementation details within a module  Makes these details inaccessible from outside the module  Isolate the implementation details of a module from other modules Isolated tasks: the implementation of task T does not affect task Q Lecture 09-10COMPSCI1054

1 Data abstraction Isolation of modules  The isolation of modules is not total (otherwise module would be useless)  Methods’ specifications, or contracts, govern how they interact with each other  Similar to having a wall hiding details, but being able to access through “hole in the wall” Lecture 09-10COMPSCI1055

1 Data abstraction Abstraction  Separates the purpose and use of a module from its implementation  A module’s specifications should  Detail how the module behaves  Identify details that can be hidden within the module   Advantages  Hides details (easier to use)  Allows us to think about the general framework (overall solution) & postpone details for later  Can easily replace implementations by better ones Lecture 09-10COMPSCI1056

1 Data abstraction Data abstraction  Asks you to think what you can do to a collection of data independently of how you do it  Allows you to develop each data structure in relative isolation from the rest of the solution  A natural extension of procedural abstraction CAR: Start() Stop() TurnLeft() TurnRight() CAR: Start(){ Select first gear Release parking brake Bring clutch up to the friction point Press gas pedal Release clutch } NOTE: Implementation can be different for different cars, e.g. automatic transmission Lecture 09-10COMPSCI1057

2 Data abstraction Abstract Data Types  An ADT is composed of  A collection of data  A set of operations on that data  Specifications of an ADT indicate  What the ADT operations do, not how to implement them  Implementation of an ADT  Includes choosing a particular data structure  ADT is a logical description of how we view the data and the operations that are allowed without regard to how they will be implemented Lecture 09-10COMPSCI1058

2 Introduction Linear Structures  Linear structures are data collections whose items are ordered depending on how they are added or removed from the structure.  Once an item is added, it stays in that position relative to the other elements that came before and came after it.  Linear structures can be thought of as having two ends, top and bottom, (or front and end or front and back)  What distinguishes one linear structure from another is the way in which items are added and removed, in particular the location where these additions and removals occur, e.g., add only to one end, add to both, etc. Lecture 09-10COMPSCI1059

2 Introduction What is a Stack?  A stack is an ordered collection of items where the addition of new items and the removal of existing items always takes place at the same end, referred to as the top of the stack.  i.e. add at top, remove from top  Last-in, first-out (LIFO) property  The last item placed on the stack will be the first item removed  Example:  A stack of dishes in a cafeteria Lecture 09-10COMPSCI10510

2 Introduction An Example  Add only to the top of a Stack  Remove only from the top of the Stack  Note: The last item placed on the stack will be the first item removed Last In - First Out (LIFO) Remove top element pop Add a new element push Remove top element pop Lecture 09-10COMPSCI10511

2 Introduction Orders  The base of the stack contains the oldest item, the one which has been there the longest.  For a stack the order in which items are removed is exactly the reverse of the order that they were placed. Lecture 09-10COMPSCI10512

2 Introduction ADT Stack Operations  What are the operations which can be used with a Stack Abstract Data?  Create an empty stack  Determine whether a stack is empty  Add a new item to the stack  push  Remove from the stack the item that was added most recently  pop  Retrieve from the stack the item that was added most recently  peek Lecture 09-10COMPSCI10513

3 The Stack ADT The Stack Abstract Data Type  Stack() creates a new stack that is empty.  It needs no parameters and returns an empty stack.  push(item) adds a new item to the top of the stack.  It needs the item and returns nothing.  pop() removes the top item from the stack.  It needs no parameters and returns the item. The stack is modified.  peek() returns the top item from the stack but does not remove it.  It needs no parameters. The stack is not modified.  is_empty() tests to see whether the stack is empty.  It needs no parameters and returns a boolean value.  size() returns the number of items on the stack.  It needs no parameters and returns an integer. Lecture 09-10COMPSCI10514

3 The Stack ADT Code Example  Code: from Stack import Stack s = Stack() print(s.is_empty()) s.push(4) s.push('dog') print(s.peek()) s.push(True) print(s.size()) print(s.is_empty()) s.push(8.4) s.pop() print(s.size()) from Stack import Stack s = Stack() print(s.is_empty()) s.push(4) s.push('dog') print(s.peek()) s.push(True) print(s.size()) print(s.is_empty()) s.push(8.4) s.pop() print(s.size()) 4 top dog 4 top True dog 4 top 8.4 True dog 4 top True dog 4 top dog 4 Lecture 09-10COMPSCI10515

3 The Stack ADT Code Example - Result  Stack operations, state of the stack, values returned s.is_empty() s.push(4) s.push('dog') s.peek() s.push(True) s.size() s.is_empty() s.push(8.4) s.pop() s.size() [] [4] [4,'dog'] [4,'dog',True] [4,'dog',True,8.4] [4,'dog',True] [4,'dog'] True 'dog' 3 False 8.4 True 2 Top Lecture 09-10COMPSCI10516

4 The Stack Implementation In Python  We use a python List data structure to implement the stack.  Remember: the addition of new items and the removal of existing items always takes place at the same end, referred to as the top of the stack.  But which “end” is better? class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def size(self): return len(self.items) def push(self, item)... def pop(self)... def peek(self)... class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def size(self): return len(self.items) def push(self, item)... def pop(self)... def peek(self)... Python List Lecture 09-10COMPSCI10517

4 The Stack Implementation Version 1  This implementation assumes that the end of the list will hold the top element of the stack.  As the stack grows, new items will be added on the END of the list. Pop operations will manipulate the same end  What is the Big-O of the push()/pop()? class Stack:... def push(self, item): self.items.append(item) def pop(self): return self.items.pop()... class Stack:... def push(self, item): self.items.append(item) def pop(self): return self.items.pop()... push(…) pop() O(1) Lecture 09-10COMPSCI10518

4 The Stack Implementation Version 2  This implementation assumes that the beginning of the list will hold the top element of the stack.  What is the Big-O of the push()/pop()? class Stack:... def push(self, item): self.items.insert(0,item) def pop(self): return self.items.pop(0)... class Stack:... def push(self, item): self.items.insert(0,item) def pop(self): return self.items.pop(0)... push(…) pop() O(n) Lecture 09-10COMPSCI10519

5 Applications Example Applications  Checking for Balanced Braces  Bracket matching  Postfix calculation  Conversion from Infix to Postfix Lecture 09-10COMPSCI10520

5 Applications 1. Checking for Balanced Braces  Using a stack to verify whether braces are balanced  An example of balanced braces  {{}{{}}}  An example of unbalanced braces  {}}{{}  Requirements for balanced braces  Each time you encounter a “}”, it matches an already encountered “{”  When you reach the end of the string, you have matched each “{” Lecture 09-10COMPSCI10521

5 Applications Balanced Braces - Algorithm  Steps: Lecture 09-10COMPSCI10522

5 Applications Balanced Braces - Examples Input string Stack as algorithm executes Lecture 09-10COMPSCI10523

5 Applications 2. Bracket Matching  Ensure that pairs of brackets are properly matched: e.g.  Other Examples: (..)..) // too many closing brackets (..(..) // too many open brackets [..(..]..) // mismatched brackets {a,(b+f[4])*3,d+f[5]} Lecture 09-10COMPSCI10524

5 Applications 2. Bracket Matching - Algorithm  Steps: Lecture 09-10COMPSCI10525

5 Applications 2. Bracket Matching - Examples Example 1: {a,(b+f[4])*3,d+f[5]} top{ ( { [ ( { ( { { [ { { Lecture 09-10COMPSCI10526

5 Applications 2. Bracket Matching - Examples Example 2: [ { ( ) ] top[ { [ ( { [ { [ [ pop: ] and { pop: ( ) Not matched!! Lecture 09-10COMPSCI10527

5 Applications 3. Postfix Calculator  Computation of arithmetic expressions can be efficiently carried out in Postfix notation with the help of stack  Infix - arg1 op arg2  Prefix - op arg1 arg2  Postfix - arg1 arg2 op (2*3)+4 2*(3+4) 2*3+4 infix 2 3 * 4 + postfix * infix Result Lecture 09-10COMPSCI10528

5 Applications 3. Postfix Calculator  Requires you to enter postfix expressions  Example: *  Steps: Lecture 09-10COMPSCI10529

5 Applications 3. Postfix Calculator - Example Evaluating the expression: * Lecture 09-10COMPSCI10530

5 Applications Example 2 key entered * s.push (2) s.push (3) s.push (4) arg2 = s.pop () arg1 = s.pop () s.push (arg1 + arg2) arg2 = s.pop () arg1 = s.pop () s.push (arg1 * arg2) top Evaluating the expression: 2 3 * 4 + Calculator action top2 Lecture 09-10COMPSCI10531

5 Applications Example 3 key entered / s.push (12) s.push (3) arg2 = s.pop () arg1 = s.pop () s.push (arg1 - arg2) i.e arg2 = s.pop () arg1 = s.pop () s.push (arg1 / arg2) i.e. 9 / 2 top12 top3 12 top Evaluating the expression: / Calculator action top9 Order is very important s.push (2) Lecture 09-10COMPSCI10532

5 Applications 4. Conversion from Infix to Postfix  Examples:  2 * =>  * 4 =>  1 * * 4 =>  Steps:  Operands always stay in the same order with respect to one another  An operator will move only “to the right” with respect to the operands  All parentheses are removed 2 3 * * * 2 4 * + Lecture 09-10COMPSCI10533

5 Applications Algorithm  operand – append it to the output string postfixExp  “(“ – push onto the stack  operator  If the stack is empty, push the operator onto the stack  If the stack is non-empty  Pop the operators of greater or equal precedence from the stack and append them to postfixExp  Stop when encounter either a “(“ or an operator of lower precedence or when the stack is empty  Push the new operator onto the stack  “)” – pop the operators off the stack and append them to the end of postfixExp until encounter the match “(“  End of the string – append the remaining contents of the stack to postfixExp Lecture 09-10COMPSCI10534

5 Applications Examples - Converting Infix to Postfix  Example 1 Exp: 2 top* Exp: 2 top* Exp: 2 3 top+ Exp: 2 3 * + has a lower precedence than * => pop *, push + top+ Exp: 2 3 * 4Exp: 2 3 * * Lecture 09-10COMPSCI10535

5 Applications Examples - Converting Infix to Postfix  Example 2: Exp: 2 top+ Exp: 2 top+ Exp: 2 3 * top+ Exp: 2 3 * top+ Exp: Exp: *Exp: * * 4 Lecture 09-10COMPSCI10536

5 Applications Conversion from Infix to Postfix a – ( b + c  d )  e Top Lecture 09-10COMPSCI10537