简体   繁体   中英

Python Evaluating Infix Notation using Stacks issue

I apologise if I seem stupid here, but I am stumped... as stated I need to have this program that evaluates infix notation expressions using stacks, but I cannot for the life of me get this thing to work out appropriately.

If anyone could help me fix my code and possibly explain where I went wrong then I would be very appreciative. Also, sorry for the wonky formatting, this is my first post and I don't fully understand the code input format.

import operator

def Main():
    #In main, necessary stacks are generated and 
    #all calculations and methods are called and preformed. 

    opStack = ArrayStack()
    numStack = ArrayStack()
    opList = ['*', '/', '+', '-']
    nums = '1234567890'
    parn = ['(', ')']
    toEval = input('Enter the Expression: ')

    toEval = toEval.split()
    #print(toEval)

    for each in toEval:

        if each in nums:
            numStack.push(each)

        if  each == parn[0]:
            opStack.push(each)

        if each in opList:            
            if each == opList[2] or opList[3]:
                opStack.push(each)

            if each == opList[0] or opList[1]:
                    while opStack.top() == (opList[2] or opList[3]) and len(opStack) > 0 and len(numStack) >= 2:
                        ans = Eval(numStack.pop(),numStack.pop(),opStack.pop())
                        numStack.push(ans)   
                        opStack.push(each)
        if each == parn[1]:
            while opStack.top() != "(":
                ans = Eval(numStack.pop(),numStack.pop(),opStack.pop()) # this line is poping the empty stack
                numStack.push(ans)
            opStack.pop()

    while opStack.is_empty() != True:
        ans = Eval(numStack.pop(),numStack.pop(),opStack.pop())
        numStack.push(ans)
    print(ans)


def Eval(num1, num2, op):
    #two numbers and an op are pulled from stacks, op checked against dict
    #dict should supply necessary 

    ops2 = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv}

    op_char = op

    op_func = ops2[op_char]

    res = op_func(float(num1), float(num2))

    return res



class ArrayStack:
# LIFO Stack implementation using a Python list as underlying storage.

    def __init__(self):
        # Create an empty stack.
        self._data = [] # nonpublic list instance

    def __len__(self):

        # Return the number of elements in the stack.

        return len(self._data)

    def is_empty(self):

        # Return True if the stack is empty.
        return len(self._data) == 0

    def push(self, e):
        # Add element e to the top of the stack.

        self._data.append(e)    # new item stored at end of list

    def top(self):
        # Return (but do not remove) the element at the top of the stack.
        # Raise Empty exception if the stack is empty.

        if self.is_empty():
            raise Empty( 'Stack is empty' )
        return self._data[-1]   # the last item in the list

    def pop(self):

        #Remove and return the element from the top of the stack (i.e., LIFO).
        #Raise Empty exception if the stack is empty. 

        if self.is_empty():
            raise Empty( 'Stack is empty' )
        return self._data.pop() # remove last item from list



Main()

These two if statements are always true:

if each == opList[2] or opList[3]:

if each == opList[0] or opList[1]:

You want something more like this:

if each == opList[2] or each == opList[3]:

And so on.

There may be other problems but that one certainly will keep your program from working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM