Beispiel #1
0
def infix_2_postfix(infix_expr):
    postfix = ""  # empty string where operands operators and popped items from stack will go
    operator_stack = Stack()  # Empty stack to push items

    for symbol in infix_expr:
        if symbol == " " or symbol == '\t':  # Ignore white spaces
            continue

        if symbol == '(':
            operator_stack.push(symbol)
        elif symbol == ')':
            top_symbol_stack = operator_stack.pop()
            while top_symbol_stack != '(':
                postfix += top_symbol_stack
                top_symbol_stack = operator_stack.pop()
        elif symbol in '+-*/%^':
            while not operator_stack.is_empty() and precedence(
                    operator_stack.peek()) >= precedence(symbol):
                # If the precedence in the stack is >= scanned symbol pop from stack and add to postfix list
                postfix += operator_stack.pop()
            operator_stack.push(
                symbol)  # When finished push the scanned symbol
        else:  # Its an operand add it to postfix string
            postfix += symbol

    while not operator_stack.is_empty():
        postfix += operator_stack.pop()
    return postfix
def infix_to_postfix(infix_expr):
    # Prec holds the precedence
    prec = {}
    prec['**'] = 4
    prec['*'] = 3
    prec['/'] = 3
    prec['+'] = 2
    prec['-'] = 2
    prec['('] = 1

    operator_stack = Stack()  # Empty stack for the operators
    postfixList = []  # Empty stack for the post fix list
    tokenList = infix_expr.split()  # Lets split the expression

    # Lets read each token
    for token in tokenList:
        if token in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' or token in '0123456789':
            # Append token to the postfixList
            postfixList.append(token)
        elif token == '(':
            # Push the token to operator stack
            operator_stack.push(token)
        elif token == ')':
            # pop last item from operator stack
            topToken = operator_stack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = operator_stack.pop()
        else:
            while (not operator_stack.is_empty()) and (
                    prec[operator_stack.peek()] >= prec[token]):
                postfixList.append(operator_stack.pop())
            operator_stack.push(token)

    while not operator_stack.is_empty():
        postfixList.append(operator_stack.pop())
    return " ".join(postfixList)