欢迎访问宙启技术站
智能推送

用Python实现基本的计算器功能

发布时间:2023-12-04 08:40:41

实现一个基本的计算器功能需要考虑用户输入的表达式的合法性和计算结果的正确性。下面是一个使用Python实现的示例代码:

def calculate(expression):
    stack = []
    operators = {'+', '-', '*', '/'}
    precedence = {'+': 1, '-': 1, '*': 2, '/': 2}

    # 将中缀表达式转换为后缀表达式
    def infix_to_postfix(expression):
        output = []
        operator_stack = []
        for char in expression:
            if char.isdigit():
                output.append(char)
            elif char in operators:
                while operator_stack and operator_stack[-1] in operators and precedence[char] <= precedence[operator_stack[-1]]:
                    output.append(operator_stack.pop())
                operator_stack.append(char)
            elif char == '(':
                operator_stack.append(char)
            elif char == ')':
                while operator_stack and operator_stack[-1] != '(':
                    output.append(operator_stack.pop())
                if operator_stack and operator_stack[-1] == '(':
                    operator_stack.pop()
        while operator_stack:
            output.append(operator_stack.pop())
        return output

    # 计算后缀表达式的结果
    def evaluate_postfix(postfix_expression):
        for char in postfix_expression:
            if char.isdigit():
                stack.append(int(char))
            elif char in operators:
                operand2 = stack.pop()
                operand1 = stack.pop()
                if char == '+':
                    stack.append(operand1 + operand2)
                elif char == '-':
                    stack.append(operand1 - operand2)
                elif char == '*':
                    stack.append(operand1 * operand2)
                elif char == '/':
                    stack.append(operand1 / operand2)
        return stack.pop()

    postfix_expression = infix_to_postfix(expression)
    result = evaluate_postfix(postfix_expression)
    return result

# 使用示例
expression = "(3+4)*5"
result = calculate(expression)
print(f"The result of {expression} is {result}.")

在以上代码中,calculate()函数接受一个表达式作为参数,并返回计算结果。代码中定义了一个栈stack用于存储操作数,一个运算符集合operators用于判断字符是否为运算符,一个运算符优先级字典precedence用于判断运算符的优先级。

该代码通过两个内部函数infix_to_postfix()evaluate_postfix()实现了中缀表达式到后缀表达式的转换和后缀表达式的求值。

首先,infix_to_postfix()函数会扫描表达式中的字符,若遇到数字,则将其添加到输出列表output中;若遇到运算符,则将其与运算符栈operator_stack中的运算符进行比较优先级,如果栈顶的运算符优先级较高,则将栈顶的运算符弹出并添加到输出列表中,直到栈顶的运算符优先级不高于当前运算符,然后将当前运算符入栈;若遇到左括号,则将其入栈;若遇到右括号,则将栈顶的运算符弹出并添加到输出列表中,直到遇到匹配的左括号,将左括号弹出但不添加到输出列表中。最后,将运算符栈中剩余的运算符按照从栈顶到栈底的顺序弹出并添加到输出列表中。

然后,evaluate_postfix()函数会从左到右扫描后缀表达式中的字符,若遇到数字,则将其入栈;若遇到运算符,则从栈中弹出两个操作数,并根据运算符对两个操作数进行计算,并将结果入栈。最后,栈中剩余的元素即为计算结果。

示例代码中,我们使用了表达式(3+4)*5进行计算,得到的结果为35

以上是一个简单的基本计算器实现,仅支持整数的加减乘除运算和括号。如果需求更复杂,可以考虑使用其他库或框架来实现。