So I need to modify the following code so that the methods PostfixEval()
and infixToPostfix()
can take floats, as well as integers with more than one digit. I've tried isinstance(token,float) == True
. Maybe I'm not using it correctly.
def infixToPostfix(infixexpr):
prec = {}
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 isinstance(token,int) == True :
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)
and
def postfixEval(postfixExpr): # also fix this to do floats
operandStack = Stack()
tokenList = postfixExpr.split()
for token in tokenList:
if isinstance(token,int) == True:
operandStack.push(int(token))
else:
operand2 = operandStack.pop()
operand1 = operandStack.pop()
result = doMath(token,operand1,operand2)
operandStack.push(result)
return operandStack.pop()
tokenList = infixexpr.split()
creates a list of strings of which none could be a float. You could make a function to cast to float returning True if you could cast to float.Then:
You can also return the float and use it in your other function:
You can use the second version in both functions. You mention float in your title so I presume you can have floats which would fail trying to cast to int.
On a side note
isinstance(token,int) == True
etc.. can simpy be writtenisinstance(token,int)
, that will be True or False so anyif isinstance(token,int)
will be evaluated correctly