现需要实现对输入法的算术表达式按照运算法则进行求值有如下要求:1表达式字符串只包含:+-非负整数空格。2当整除除法不能整除时需向上取整。请帮我写出对应的比较简单的python代码。
可以使用栈来实现对算术表达式的求值。
具体步骤如下:
- 定义一个操作数栈和一个操作符栈。
- 遍历表达式字符串,依次处理每个字符。
- 如果当前字符是空格,则跳过。
- 如果当前字符是数字,则读取完整的整数,并将其压入操作数栈。
- 如果当前字符是运算符(+、-、*、/),则将其与操作符栈的栈顶元素进行比较:
- 如果操作符栈为空,或者栈顶元素是左括号"(",则将当前运算符压入操作符栈。
- 如果当前运算符的优先级大于栈顶元素的优先级,则将当前运算符压入操作符栈。
- 否则,将操作符栈的栈顶元素弹出,并从操作数栈中弹出两个操作数,进行相应的计算,将结果压入操作数栈。继续比较当前运算符与新的操作符栈的栈顶元素。
- 如果当前字符是左括号"(",则将其压入操作符栈。
- 如果当前字符是右括号")",则不断从操作符栈中弹出运算符,直到遇到左括号"("为止。然后,从操作数栈中弹出两个操作数,进行相应的计算,将结果压入操作数栈。
- 遍历完整个表达式字符串后,如果操作符栈不为空,则不断从操作符栈中弹出运算符,并从操作数栈中弹出两个操作数,进行相应的计算,将结果压入操作数栈。
- 最后,操作数栈中的唯一元素即为表达式的最终求值结果。
下面是实现这一算法的Python代码:
def calculate(expression):
operators = []
operands = []
priority = {'+': 0, '-': 0, '*': 1, '/': 1}
def apply_operator():
operator = operators.pop()
operand2 = operands.pop()
operand1 = operands.pop()
if operator == '+':
result = operand1 + operand2
elif operator == '-':
result = operand1 - operand2
elif operator == '*':
result = operand1 * operand2
elif operator == '/':
result = -(-operand1 // operand2) if operand1 < 0 else operand1 // operand2
operands.append(result)
i = 0
while i < len(expression):
if expression[i].isspace():
i += 1
continue
elif expression[i].isdigit():
j = i
while j < len(expression) and expression[j].isdigit():
j += 1
operands.append(int(expression[i:j]))
i = j
elif expression[i] in ('+', '-', '*', '/'):
while operators and operators[-1] != '(' and priority[expression[i]] <= priority[operators[-1]]:
apply_operator()
operators.append(expression[i])
i += 1
elif expression[i] == '(':
operators.append(expression[i])
i += 1
elif expression[i] == ')':
while operators[-1] != '(':
apply_operator()
operators.pop()
i += 1
while operators:
apply_operator()
return operands[0]
expression = input("请输入算术表达式:")
result = calculate(expression)
print("计算结果为:", result)
使用示例:
请输入算术表达式:(3 + 4) * 5 - 2 / 2
计算结果为: 34
注意:以上代码实现了对输入表达式的求值,但未对输入的表达式进行合法性检查。如果输入的表达式不符合要求,可能会导致程序出错。在实际应用中,建议对输入的表达式进行合法性检查,以保证程序的稳定性
原文地址: http://www.cveoy.top/t/topic/inI3 著作权归作者所有。请勿转载和采集!