Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computer Science 112 Fundamentals of Programming II Applications of Stacks.

Similar presentations


Presentation on theme: "Computer Science 112 Fundamentals of Programming II Applications of Stacks."— Presentation transcript:

1 Computer Science 112 Fundamentals of Programming II Applications of Stacks

2 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 5 + 45 4 +9 5 + 4 * 25 4 2 * +13 (5 + 4) * 25 4 + 2 *18 5 + 4 - 35 4 + 3 -6

3 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.)

4 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

5 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

6 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

7 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

8 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

9 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

10 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

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

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

13 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

14 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

15 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

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

17 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

18 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

19 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

20 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

21 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

22 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

23 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

24 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

25 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

26 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

27 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

28 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

29 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

30 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

31 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

32 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

33 For Wednesday More stack applications


Download ppt "Computer Science 112 Fundamentals of Programming II Applications of Stacks."

Similar presentations


Ads by Google