Computer Science 112 Fundamentals of Programming II Applications of Stacks.

Post on 14-Dec-2015

219 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

Transcript

Computer Science 112

Fundamentals of Programming IIApplications of Stacks

Evaluating Postfix ExpressionsExpressions in postfix notation are easier for a computerto evaluate than expressions in infix notation.

In postfix notation, the operands precede the operator.

Infix Postfix Value

5 + 4 5 4 + 9

5 + 4 * 2 5 4 2 * + 13

(5 + 4) * 2 5 4 + 2 * 18

5 + 4 - 3 5 4 + 3 - 6

The Setup

Scanner Evaluator

User inputstrings

Sequence oftokens

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 stackFor 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

Scanner Evaluator

User inputstring

Sequence oftokens

Value

A token is either an operand (a number) or an operator (+, -, etc.)

Translator

Sequence oftokens

infix postfix

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 stackCreate a new postfix expressionWhile 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 stackCreate 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 stackCreate a new postfix expressionWhile 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 stackCreate a new postfix expressionWhile 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 stackCreate a new postfix expressionWhile 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_PAR 0– Token.R_PAR 0– Token.PLUS 1– Token.MINUS 1– Token.MUL 2– Token.DIV 2– Token.EXPO 3

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

top related