Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "COMPSCI 105 SS 2015 Principles of Computer Science 09 ADT & Stacks."— Presentation transcript:

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

2 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

3 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

4 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

5 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

6 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

7 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

8 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

9 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

10 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

11 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) 34 57 12 34 57 12 103 34 57 12 34 57 Remove top element pop Add a new element push Remove top element pop Lecture 09-10COMPSCI10511

12 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

13 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

14 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

15 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

16 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

17 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

18 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

19 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

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

21 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

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

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

24 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

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

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

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

28 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 2 3 4 + * infix Result 10 14 Lecture 09-10COMPSCI10528

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

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

31 5 Applications Example 2 key entered 2 3 4 + * 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) top2 3 2 4 3 2 7 2 14 Evaluating the expression: 2 3 * 4 + Calculator action top2 Lecture 09-10COMPSCI10531

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

33 5 Applications 4. Conversion from Infix to Postfix  Examples:  2 * 3 + 4 =>  2 + 3 * 4 =>  1 * 3 + 2 * 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 * 4 + 2 3 4 * + 1 3 * 2 4 * + Lecture 09-10COMPSCI10533

34 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

35 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 * 4 + 2 * 3 + 4 Lecture 09-10COMPSCI10535

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

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


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

Similar presentations


Ads by Google