如何读取双位数字而不是单位数字?
我正在创建一个后缀计算器,可以进行简单的加、减、乘、除运算。运行这段代码时,使用两个单个数字的计算是没问题的。但是,当我使用双位数(比如15、20等)时,它把这个数字存储成了['1', '5'],而不是15,这样就导致运算出错了。我该怎么解决这个问题呢?
evaluation = Stack()
def main():
expression = str(input("Enter an expression: "))
expression = expression.replace(" ","")
for x in expression:
evaluation.push(x)
while len(evaluation) > 1:
check = evaluation.pop()
if check == "+":
first = evaluation.pop()
second = evaluation.pop()
temp = int(second) + int(first)
evaluation.push(temp)
elif check == "-":
first = evaluation.pop()
second = evaluation.pop()
temp = int(second) - int(first)
evaluation.push(temp)
elif check == "/":
first = evaluation.pop()
second = evaluation.pop()
temp = int(second) / int(first)
evaluation.push(temp)
elif check == "*":
first = evaluation.pop()
second = evaluation.pop()
temp = int(second) * int(first)
evaluation.push(temp)
elif check != "+" or check != "-" or check != "*" or check != "/":
evaluation.push(check)
print("Answer:", evaluation.data[0])
4 个回答
0
你可以使用正则表达式:
expression = "1234+567"
sign_index = [m.start() for m in re.finditer(r'[+-/*]', expression)][0]
sign = expression[sign_index]
first_num = int(expression.split(sign)[0])
second_num = int(expression.split(sign)[1])
0
我觉得你遇到问题是因为你在逐个字符地处理输入。
我建议你可以做两件事中的一件: - 把输入分开来处理,比如先问第一个数字、运算符,然后再问第二个数字。 - 逐个字符地查看输入内容,判断每个字符是什么,然后进行相应的处理。
记住,你需要考虑运算符可能是一个反斜杠(\),如果你用它来处理两个整数,你得到的结果会是整数,而不是浮点数,这样可能更合适。
0
当你到达这个地方:
elif check != "+" or check != "-" or check != "*" or check != "/":
evaluation.push(check)
你实际上是把一个符号放进了你的栈里。
你可以做的另一种方法是,继续读取符号(数字),直到遇到其他东西为止,然后把你读取的整个字符串转换成一个整数,再放进栈里。
0
不要把表达式中的空格去掉,而是要利用这些空格来分割
表达式,变成可以使用的部分:
In [1]: '223 370 * 45 /'.split()
Out[1]: ['223', '370', '*', '45', '/']
接下来,遍历你现在得到的列表。要检查列表中的某个项目是不是运算符,你可以简单地用in
来判断:
In [4]: '+' in '+-/*'
Out[4]: True
如果这个项目不是运算符,那它一定是个数字,所以用float()
把它转换成浮点数,然后放到栈里。
因为你已经定义了所有的运算符,所以只需要把操作数弹出一次。而且,普通的数学运算符也可以作为函数使用,所以你可以用字典来调用它们,这样就不用写一大堆的if/elif了;
In [1]: from operator import add, sub, mul, div
In [2]: ops = {'+': add, '-': sub, '*': mul, '/': div}
In [3]: ops['+'](1, 3)
Out[3]: 4
In [4]: ops['/'](1.0, 3.0)
Out[4]: 0.3333333333333333
所以,一个简单的计算器函数可以这样写:
from operator import add, sub, mul, div
_ops = {'+': add, '-': sub, '*': mul, '/': div}
def postfix(expr):
"""Evaluate a postsfix expression
:param expr: The expression to evaluate
:returns: result of the expression
"""
items = expr.split()
if not items:
raise ValueError("Empty expression")
stk = [] # A plain list works fine here.
for i in items:
if i not in '+-*/':
# float() will raise an exception if it doesn't find a number.
stk.append(float(i))
else:
try:
b = stk.pop()
a = stk.pop()
stk.append(_ops[i](a, b))
except IndexError:
raise ValueError('Invalid expression; empty stack')
return stk[-1]