如何用两位数而不是一位数来读?

2024-05-17 02:37:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个postfix计算器,它可以执行简单的(+,-,*,/)操作。运行此代码并使用两个单个数字可以正常工作。但是,使用一个两位数(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])

Tags: or代码check数字poppushtemppostfix
3条回答

当你说到这一点时:

elif check != "+" or check != "-" or check != "*" or check != "/":
        evaluation.push(check)

实际上,您将一个符号放入堆栈中。 相反,您可以继续读取符号(数字),直到没有遇到其他东西,然后将读取的整个字符串转换为整数并将其推送。在

可以使用正则表达式:

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])

我认为您遇到了麻烦,因为您正在迭代输入中的每个字符。在

我会做两件事中的一件: -分解输入-分别要求输入第一个数字、操作和第二个数字 -迭代输入中的每个字符并确定它是什么,然后对其进行更正。在

请记住,您要确保运算符可能是\的,如果您在两个int上使用它,您将得到一个int而不是一个float,这可能更合适。在

相关问题 更多 >