1 / 33

Computer Science 112

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. The Setup.

emery-pena
Download Presentation

Computer Science 112

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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.

  3. The Setup User input strings Sequence of tokens Values Scanner Evaluator 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. The Scanner Interface 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

  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. Algorithm for the Evaluator 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)

  9. Python Code defevaluate(source): stack = LinkedStack() forcurrentTokenin source: ifcurrentToken.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() returnresult.getValue()

  10. 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: raiseZeroDivisionError result = left // right return result

  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 User input string Sequence of tokens Sequence of tokens Value Scanner Translator Evaluator infix postfix A token is either an operand (a number) or an operator (+, -, etc.)

  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. Algorithm for the Translator 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 Move operands to the postfix expression

  26. Algorithm for the Translator 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 Move left parenthesis to the stack

  27. Algorithm for the Translator 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 Shift operators before the right parenthesis from the stack to the postfix expression

  28. Algorithm for the Translator 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 Shift operators with higher or equal priority from the stack to the postfix expression

  29. Algorithm for the Translator 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

  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_PAR 0 • Token.R_PAR 0 • Token.PLUS 1 • Token.MINUS 1 • Token.MUL 2 • Token.DIV 2 • Token.EXPO 3

  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

More Related