[Tutor] infix to postfix eval

Quiles, Stephanie stephanie.quiles001 at albright.edu
Sun Aug 2 06:09:36 CEST 2015


hello again!

I have to unify these methods so that i can enter an infix, convert it to a postfix and then solve. Here are the methods

method #1 is :


class Stack:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def push(self, item):
        self.items.insert(0,item)

    def pop(self):
        return self.items.pop(0)

    def peek(self):
        return self.items[0]

    def size(self):
        return len(self.items)


def infixToPostfix(infixexpr):
    prec = {}
    prec["^"] = 4
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                  postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)

print(infixToPostfix("5 * 3 ^ ( 4 - 2 )"))
print(infixToPostfix("( A + B ) * C - ( D - E ) * ( F + G )”))


method #2 is :

def postfixEval(postfixExpr):
    operandStack = Stack()

    tokenList = postfixExpr.split()

    for token in tokenList:
        if token in "0123456789":
            operandStack.push(int(token))
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token,operand1,operand2)
            operandStack.push(result)

    return operandStack.pop()

def doMath(op, op1, op2):
    if op == "^":
        return op1 ** op2
    if op == "*":
        return op1 * op2
    elif op == "/":
        return op1 / op2
    elif op == "+":
        return op1 + op2
    else:
        return op1 - op2

basically i have to make a main function and somehow unify these two so that user can input an infix, then convert and print the postfix and then solve and print the final calculation. Here is the assignment as written by the instructor:

Try to do program #3 from P.144. We began this in class. Here’s what you need to do. We will be using Listings 3.7 and 3.8. First make sure that you can get Listing 3.7 to work. Just test some strings. Note that the code in the text expects the input to be “strings” of letters, each character separated by a space, and uses the “uppercase” statement in its definition. Second make sure that you can get Listing 3.8 to work. Just test some strings. This one you will test with digits. Third, now what you’ll need to do to answer program #3 is to get Listing 3.7 to handle digits rather than letters. This should not require a great deal of change to the code. Look at how Listing 3.8 handles the digits and see if you can duplicate that. Test some simple examples (limit the values from 0 – 9) with each character (token) separated by a space. For example, if we received the input of “3 + 4 * 2”, we would output 3 4 2 * +. (NOTE THE SPACES.) Fourth, once you have this working, you will simply feed this result to Listing 3.8 and the evaluated result should be printed. For example, if we received the input of “3 + 4 * 2”, we would output 3 4 2 * + and also output the value of 11.

Below is a sample of what you could show. Keep it simple.


            print ("This program will accept an infix expression,")
            print ("convert to postfix, and evaluate the result.")
            print ("No input validation will be performed.")
            print ("Please enter the infix expression correctly, as follows:")
            print ("Enter only numbers 0-9")
            print ("Separate each character with a space")
            print ("You can use the following operators: ( ) + - * / ")
            print ("For example: ( 8 + 2 ) * ( 2 + 4 )")

            Here’s how a sample run would look.

This program will accept an infix expression,
convert to postfix, and evaluate the result.
No input validation will be performed.
Please enter the infix expression correctly, as follows:
Enter only numbers 0-9
Separate each character with a space
You can use the following operators: ( ) + - * /
For example: ( 8 + 2 ) * ( 2 + 4 )

Enter infix string: ( 8 + 2 ) * ( 2 + 4 )
The postfix string is:  8 2 + 2 4 + *
The final result is:  60

Thanks!



More information about the Tutor mailing list