【发布时间】:2015-06-12 02:31:59
【问题描述】:
所以我需要修改以下代码,使PostfixEval() 和infixToPostfix() 方法可以采用浮点数,以及多于一位的整数。我试过isinstance(token,float) == True。也许我没有正确使用它。
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)
和
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()
【问题讨论】:
-
你试过内置的 type() 吗?
-
@msanti 不,我没有,而且对 python 太陌生了,我不能说我知道如何使用它哈哈。感谢您的反馈!
-
type() 方法返回某个变量的类型。例如,type(3.14) 将返回一个浮点数。所以我可以通过执行 if type(somevariable) == float: do something 来测试某物是浮点数还是任何数据类型
标签: python isinstance