Skip to content Skip to sidebar Skip to footer

Evaluating An Infix Expression Python

My task is to evaluate a fully parenthesized infix expression using a stack. A Stack class has been written for me and I must not change or modify the Stack class. Here are the st

Solution 1:

I think the problem is that you did't decide what you wan't to put on your stack. Are there number or strings ? I don't think it is the best solution (you are clearly doing some class assignment and I don't want to give you the solution), but if you decide to put only strings then, you just have to replace:

xStack.push(evaluation)

by

xStack.push(str(evaluation))

But as already said in the commentary, you should probably not use eval and put integers and operators on the stack.

Solution 2:

The issue is that in your code, the two sets of '9+9' are evaluated as strings in eval, then put back into the stack as integers. (see below)

theStack=['(', 18, '+', 18]

Therefore, in the line of code:

math=xStack.pop()+xStack.pop()+xStack.pop()

it tries to concatenate two integers (18 and 18) and a string ('+'), creating an error as these are incompatible types. If you changed this line to:

math=str(xStack.pop())+str(xStack.pop())+str(xStack.pop())

Therefore forcing everything to be one type, string, it should work fine.

Solution 3:

I hope this would help to you

see the gist

Post a Comment for "Evaluating An Infix Expression Python"