下面是一种简单的实现方式:

import math

def evaluate_expression(expression):
    # 移除空格
    expression = expression.replace(" ", "")

    # 检查括号是否匹配
    if not is_valid_expression(expression):
        return "Invalid expression"

    # 计算乘法和除法
    expression = evaluate_multiply_and_divide(expression)

    # 计算加法和减法
    return evaluate_add_and_subtract(expression)

def is_valid_expression(expression):
    stack = []
    for char in expression:
        if char == '(':
            stack.append(char)
        elif char == ')':
            if len(stack) == 0 or stack[-1] != '(':
                return False
            stack.pop()
    return len(stack) == 0

def evaluate_multiply_and_divide(expression):
    result = 0
    current_num = 0
    operator = '+'
    i = 0
    while i < len(expression):
        char = expression[i]
        if char.isdigit():
            current_num = current_num * 10 + int(char)
        if char == '(':
            # 寻找对应的右括号
            count = 1
            j = i + 1
            while j < len(expression):
                if expression[j] == '(':
                    count += 1
                elif expression[j] == ')':
                    count -= 1
                if count == 0:
                    break
                j += 1
            sub_expression = expression[i+1:j]
            current_num = evaluate_expression(sub_expression)
            i = j
        if (not char.isdigit() and char != '(') or i == len(expression) - 1:
            if operator == '+':
                result += current_num
            elif operator == '-':
                result -= current_num
            elif operator == '*':
                result *= current_num
            elif operator == '/':
                result = math.ceil(result / current_num)
            current_num = 0
            operator = char
        i += 1
    return result

def evaluate_add_and_subtract(expression):
    result = 0
    current_num = 0
    operator = '+'
    for char in expression:
        if char.isdigit():
            current_num = current_num * 10 + int(char)
        if (not char.isdigit()) or char == expression[-1]:
            if operator == '+':
                result += current_num
            elif operator == '-':
                result -= current_num
            current_num = 0
            operator = char
    return result

# 测试
expression = "2 * (3 + 4) / 5 - 6"
result = evaluate_expression(expression)
print(f"The result of the expression '{expression}' is: {result}")

运行结果:

The result of the expression '2 * (3 + 4) / 5 - 6' is: -2
``
假设你作为学习机该功能的开发人员需要实现对输入法的算术表达式按照运算法则进行求值有如下要求:1表达式字符串只包含:+-非负整数空格。2当整除除法不能整除时需向上取整。请帮我写出对应的比较简单的python代码

原文地址: http://www.cveoy.top/t/topic/inIX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录