Computer Science 112 Fundamentals of Programming II Applications of Stacks.

Slides:



Advertisements
Similar presentations
INFIX, PREFIX, & POSTFIX EXPRESSIONS. Infix Notation We usually write algebraic expressions like this: a + b This is called infix notation, because the.
Advertisements

Stacks Chapter 11.
Stacks - 3 Nour El-Kadri CSI Evaluating arithmetic expressions Stack-based algorithms are used for syntactical analysis (parsing). For example.
Prefix, Postfix, Infix Notation
Arithmetic Expressions Infix form –operand operator operand 2+3 or a+b –Need precedence rules –May use parentheses 4*(3+5) or a*(b+c)
COSC 2006 Chapter 7 Stacks III
COMPSCI 105 S Principles of Computer Science 13 Stacks.
C o n f i d e n t i a l Developed By Nitendra NextHome Subject Name: Data Structure Using C Title : Overview of Stack.
Lecture 12 – ADTs and Stacks.  Modularity  Divide the program into smaller parts  Advantages  Keeps the complexity managable  Isolates errors (parts.
Arithmetic Expressions
Topic 15 Implementing and Using Stacks
Stacks & Queues Infix Calculator CSC 172 SPRING 2002 LECTURE 5.
Infix to postfix conversion Process the tokens from a vector infixVect of tokens (strings) of an infix expression one by one When the token is an operand.
Infix, Postfix, Prefix.
Lecture 8 Feb 19 Goals: l applications of stack l Postfix expression evaluation l Convert infix to postfix l possibly start discussing queue.
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,
CS 206 Introduction to Computer Science II 03 / 16 / 2009 Instructor: Michael Eckmann.
1 CSCD 326 Data Structures I Infix Expressions. 2 Infix Expressions Binary operators appear between operands: W - X / Y - Z Order of evaluation is determined.
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.
Infix to postfix conversion Use a loop to read the tokens one by one from a vector infixVect of tokens (strings) representing an infix expression. For.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Computer Science 112 Fundamentals of Programming II Expression Trees.
Computer Science 112 Fundamentals of Programming II Recursive Processing of Languages.
Data Structures Lecture : Stacks (Infix, Postfix and Prefix Expressions) Azhar Maqsood NUST Institute of Information Technology (NIIT)
Fundamentals of Python: From First Programs Through Data Structures Chapter 14 Linear Collections: Stacks.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Stack Applications.
1 Stacks Chapter 4 2 Introduction Consider a program to model a switching yard –Has main line and siding –Cars may be shunted, removed at any time.
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.
Computer Science 112 Fundamentals of Programming II Introduction to Stacks.
Computer Science Department Data Structure & Algorithms Problem Solving with Stack.
CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM.
Chapter 6 B Stacks. © 2004 Pearson Addison-Wesley. All rights reserved6 B-2 Comparing Implementations All of the three implementations are ultimately.
Basic Data Structures Stacks. A collection of objects Objects can be inserted into or removed from the collection at one end (top) First-in-last-out.
Stacks An Abstract Data Type. Restricted Access Unlike arrays, stacks only allow the top most item to be accessed at any time The interface of a stack.
CHP-3 STACKS.
Prefix, Postfix, Infix Notation. Infix Notation  To add A, B, we write A+B  To multiply A, B, we write A*B  The operators ('+' and '*') go in between.
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.
DATA STRUCTURES Application of Stack – Infix to Postfix conversion a Joshua Presentation.
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(),
CSC 172 DATA STRUCTURES. A TALE OF TWO STRUCTURES.
BCA II Data Structure Using C
Review Use of Stack Introduction Stack in our life Stack 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.
Revised based on textbook author’s notes.
COMPSCI 107 Computer Science Fundamentals
Fundamentals of Programming II Recursive Processing of Languages
Infix to postfix conversion
CSC 172 DATA STRUCTURES.
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Stacks Chapter 4.
Stack application: postponing data usage
PART II STACK APPLICATIONS
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Lecture No.07 Data Structures Dr. Sohail Aslam
Infix to Postfix Conversion
Queue Applications Lecture 31 Mon, Apr 9, 2007.
Infix to Postfix Conversion
Topic 15 Implementing and Using Stacks
(Part 2) Infix, Prefix & Postfix
Stack.
Queue Applications Lecture 31 Tue, Apr 11, 2006.
Data Structures and Algorithms 2/2561
17CS1102 DATA STRUCTURES © 2016 KL University – The contents of this presentation are an intellectual and copyrighted property of KL University. ALL RIGHTS.
Chapter 7 (continued) © 2011 Pearson Addison-Wesley. All rights reserved.
Stacks A stack is an ordered set of elements, for which only the last element placed into the stack is accessible. The stack data type is also known as.
Presentation transcript:

Computer Science 112 Fundamentals of Programming II Applications of Stacks

Evaluating Postfix Expressions Expressions in postfix notation are easier for a computer to evaluate than expressions in infix notation. In postfix notation, the operands precede the operator. InfixPostfixValue * * +13 (5 + 4) * *

The Setup ScannerEvaluator User input strings Sequence of tokens Values We assume for now that the user enters input in postfix notation A token is either an operand (a number) or an operator (+, -, etc.)

Scanner(aString)Creates a scanner on a source string hasNext()True if more tokens, false otherwise next()Advances and returns the next token iter(aScanner)Supports for loop The Scanner Interface

Tokens A Token object has two attributes: –type (indicating an operand or operator) –value (an int if it ’ s an operand, or the source string otherwise) Token types are –Token.INT –Token.PLUS –Token.MINUS –Token.MUL –Token.DIV –Token.UNKNOWN

The Token Interface Token(source)Creates a token from a source string str(aToken)String representation isOperator()True if an operator, false otherwise getType()Returns the type getValue()Returns the value

Strategy Scan the postfix expression from left to right, extracting individual tokens as we go If the next token is an operand, push it onto the stack If the next token is an operator –Pop the top two operands from the stack –Apply the operator to them and push the result onto the stack The operand left on the stack at the end of the process is the expression ’ s value

Create a new stack For each token in scanner If the token is an operand Push the token onto the stack Else if the token is an operator Pop the top two tokens from the stack (two operands) Use the current token to evaluate the two operands just popped Push the result onto the stack (an operand) Return the top item on the stack (the result value) Algorithm for the Evaluator

def evaluate(source): stack = LinkedStack() for currentToken in source: if currentToken.getType() == Token.INT: stack.push(currentToken) else: right = stack.pop() # Right operand went on last. left = stack.pop() result = Token(computeValue(currentToken, left.getValue(), right.getValue())) stack.push(result) result = stack.pop() return result.getValue() Python Code

def computeValue(op, left, right): opType = op.getType() if opType == Token.PLUS: result = left + right elif opType == Token.MINUS: result = left – right elif opType == Token.MUL: result = left * right elif opType == Token.DIV: if right == 0: raise ZeroDivisionError result = left // right return result Python Code

Converting Infix to Postfix Completely parenthesize the infix expression Move each operator to the space held by the corresponding right parenthesis Remove all parentheses

Example Conversion A / B ^ C + D * E – A * C ^ means exponentiation, which has a higher priority than multiplication

Example Conversion A / B ^ C + D * E – A * C (((A / (B ^ C)) + (D * E)) – (A * C)) Fully parenthesize and locate the places to which the operators should be moved

Example Conversion A / B ^ C + D * E – A * C (((A / (B ^ C)) + (D * E)) – (A * C)) (((A (B C ^) /) (D E *) +) (A C *) –) Move the operators

Example Conversion A / B ^ C + D * E – A * C (((A / (B ^ C)) + (D * E)) – (A * C)) (((A (B C ^) /) (D E *) +) (A C *) –) A B C ^ / D E * + A C * – Remove the parentheses

A Complete Expression Interpreter Takes an infix expression as input Converts the infix expression to a postfix expression Evaluates the postfix expression

The Setup ScannerEvaluator User input string Sequence of tokens Value A token is either an operand (a number) or an operator (+, -, etc.) Translator Sequence of tokens infixpostfix

Strategy for the Translator Start with an empty postfix expression and an empty stack which will hold operators and left parentheses Scan across the infix expression from left to right

Strategy for the Translator Start with an empty postfix expression and an empty stack which will hold operators and left parentheses Scan across the infix expression from left to right On encountering an operand, append it to the postfix expression

Strategy for the Translator Start with an empty postfix expression and an empty stack which will hold operators and left parentheses Scan across the infix expression from left to right On encountering an operand, append it to the postfix expression On encountering a left parenthesis, push it onto the stack

Strategy for the Translator Start with an empty postfix expression and an empty stack which will hold operators and left parentheses Scan across the infix expression from left to right On encountering an operand, append it to the postfix expression On encountering a left parenthesis, push it onto the stack On encountering a right parenthesis, shift operators from the stack to the postfix expression until reaching a left parenthesis, which is thrown away

Strategy for the Translator Start with an empty postfix expression and an empty stack which will hold operators and left parentheses Scan across the infix expression from left to right On encountering an operand, append it to the postfix expression On encountering a left parenthesis, push it onto the stack On encountering a right parenthesis, shift operators from the stack to the postfix expression until reaching a left parenthesis, which is thrown away On encountering an operator, pop all the operators having a greater or equal precedence, append them to the postfix expression, and push the current operator onto the stack

Strategy for the Translator Start with an empty postfix expression and an empty stack which will hold operators and left parentheses Scan across the infix expression from left to right On encountering an operand, append it to the postfix expression On encountering a left parenthesis, push it onto the stack On encountering a right parenthesis, shift operators from the stack to the postfix expression until reaching a left parenthesis, which is thrown away On encountering an operator, pop all the operators having a greater or equal precedence, append them to the postfix expression, and push the current operator onto the stack On encountering the end of the infix expression, transfer the remaining operators from the stack to the postfix expression

Data Structures Used Scanner is iterable over tokens (the infix expression) Translator uses a list to represent the postfix expression Translator is iterable over tokens (the postfix expression) Translator and evaluator each use a local stack

Create a new stack Create a new postfix expression While there are more tokens Get the next token If the token is an operand Append it to the postfix expression Algorithm for the Translator Move operands to the postfix expression

Create a new stack Create a new postfix expression While there are more tokens Get the next token If the token is an operand Append it to the postfix expression Else if the token is a left parenthesis Push it onto the stack Algorithm for the Translator Move left parenthesis to the stack

Create a new stack Create a new postfix expression While there are more tokens Get the next token If the token is an operand Append it to the postfix expression Else if the token is a left parenthesis Push it onto the stack Else if the token is a right parenthesis Do Pop an operator from the stack If the operator is not a left parenthesis Append the operator to the postfix expression While the operator is not a left parenthesis Algorithm for the Translator Shift operators before the right parenthesis from the stack to the postfix expression

Create a new stack Create a new postfix expression While there are more tokens Get the next token If the token is an operand Append it to the postfix expression Else if the token is a left parenthesis Push it onto the stack Else if the token is a right parenthesis Do Pop an operator from the stack If the operator is not a left parenthesis Append the operator to the postfix expression While the operator is not a left parenthesis Else While the stack is not empty and the priority of the operator at the top of the stack >= the current token’s priority Pop the operator Append the operator to the postfix expression Push the current token onto the stack Algorithm for the Translator Shift operators with higher or equal priority from the stack to the postfix expression

Create a new stack Create a new postfix expression While there are more tokens Get the next token If the token is an operand Append it to the postfix expression Else if the token is a left parenthesis Push it onto the stack Else if the token is a right parenthesis Do Pop an operator from the stack If the operator is not a left parenthesis Append the operator to the postfix expression While the operator is not a left parenthesis Else While the stack is not empty and the priority of the operator at the top of the stack >= the current token’s priority Pop the operator Append the operator to the postfix expression Push the current token onto the stack While the stack is not empty Pop the operator from the stack Append the operator to the postfix expression Algorithm for the Translator

Syntax Errors? The translator ’ s algorithm assumes that the input expression is in syntactically correct infix form The translator ’ s algorithm can detect some syntax errors, for example, if its stack is empty when it shouldn ’ t be To catch all of the possible syntax errors, more machinery is required

Operator Priority The getPriority() method returns the priority of an operator token Priority values: –Token.L_PAR0 –Token.R_PAR0 –Token.PLUS1 –Token.MINUS1 –Token.MUL2 –Token.DIV2 –Token.EXPO3

Right Association ^ is right-associative 2^2^3 is 2^(2^3) = 2^8 = 256, not (2^2)^3 = 4^3 = 64 We can retain the ^ operator on the stack until an operator of strictly lower priority is encountered

For Wednesday More stack applications