给定一个字符串描述的算术表达式,计算出结果值。
输入字符串长度不超过 100 ,合法的字符包括 ”+, -, *, /, (, )” , ”0-9” 。
数据范围:运算过程中和最终结果均满足
,即只进行整型运算,确保输入的表达式合法
# 基于栈求解 逆波兰表达式
import re
yxj = {"+":1,"-":1,"*":2,"/":2,"(":3,")":0}
def evaluate_expression(s: str) -> int:
# 将表达式中的 `{}` 和 `[]` 替换成 `()`
s = s.replace("{", "(").replace("}", ")")
s = s.replace("[", "(").replace("]", ")")
# 拆分成数字和符号的list
expression_list = re.findall(r'-?\d+|[+*/()-{}[\]]', s)
temp = []
for i in range(len(expression_list)):
if i>0 and len(expression_list[i])>1 and \
expression_list[i][0]=="-" and expression_list[i-1]!="(":
temp.append("-")
temp.append(expression_list[i][1:])
else:
temp.append(expression_list[i])
expression_list = temp
# print(expression_list)
# 生成 逆波兰表达式
nb_exp = []
ops = []
for s in expression_list:
# print(nb_exp)
# print(ops)
if s.isdigit()&nbs***bsp;s[1:].isdigit():
nb_exp.append(s)
elif s in ("*","/","+","-","("):
if len(ops)==0&nbs***bsp;(len(ops)!=0 and yxj[ops[-1]]<yxj[s])&nbs***bsp;ops[-1]=="(":
ops.append(s)
else:
while yxj[s]<= yxj[ops[-1]] and ops[-1] != "(":
nb_exp.append(ops.pop())
if len(ops)==0:
break
ops.append(s)
elif s == ')':
while ops[-1] != "(":
nb_exp.append(ops.pop())
ops.pop() # 弹出“(”
while ops != []:
nb_exp.append(ops.pop())
# print(nb_exp)
# 求值
res = []
for s in nb_exp:
if s.isdigit()&nbs***bsp;s[1:].isdigit():
res.append(s)
else:
right = float(res.pop())
left = float(res.pop())
if s=="+":
res.append(right+left)
if s=="-":
res.append(left-right)
if s=="*":
res.append(right*left)
if s=="/":
res.append(left/right)
return res[0]
s = input().strip()
print(int(evaluate_expression(s)))
import sys
s=input()
def compute(lst):#计算无括号列表的值如:['1','+','2','*','-3','/','2','-','4'],
s=[]
for i in lst:#先计算乘除法
if s and (i.isnumeric()&nbs***bsp;(i[0]=='-' and len(i)>1)) and s[-1] in ['*','/']:#如果i为正数或负数字符串且上一个符号为乘号或除号
if s[-1]=='*':
s[-2:]=[str(int(s[-2])*int(i))]
if s[-1]=='/':
s[-2:]=[str(int(s[-2])//int(i))]
else:
s.append(i)
s1=[]
for i in s:#计算加减法
if s1 and s1 and (i.isnumeric()&nbs***bsp;(i[0]=='-' and len(i)>1)):
if s1[-1]=='+':
s1[-2:]=[str(int(s1[-2])+int(i))]
if s1[-1]=='-':
s1[-2:]=[str(int(s1[-2])-int(i))]
else:
s1.append(i)
return int(s1[0])
def f(s):
#为便于计算,在-前加0
if s[0]=='-':
s=('0'+s)
while '(-' in s:
s=s.replace('(-','(0-')
lst=[]
for c in s:
if lst:
if lst[-1].isnumeric() and c!=')':
if c.isnumeric():
lst[-1]+=c
else:
lst.append(c)
else:
if c==')':
i=len(lst)-1
while lst[i]!='(':#计算上一个左括号的位置
i-=1
temp=lst[i+1:]
lst[i:]=[str(compute(temp))]#计算括号内的值并添加到列表末尾
else:
lst.append(c)
else:
lst.append(c)
#print('lst:',lst)
return compute(lst)
print(f(s)) #考虑了有负数的情况
s = input()
prior = {"(": 0, "+": 1, "-": 1, "/": 2, "*": 2, ")": 3}
s = list(s.strip(" "))
num_stack = []
op_stack = []
def tow_num():
if len(num_stack) > 0:
num2, num1 = num_stack.pop(), num_stack.pop()
op = op_stack.pop()
if op == "+":
num_stack.append((num1 + num2))
if op == "-":
num_stack.append((num1 - num2))
if op == "*":
num_stack.append((num1 * num2))
if op == "/":
num_stack.append((num1 // num2))
i = 0
while i < len(s):
c = s[i]
if c.isdigit():
num = 0
pos = 0
if (
i != 0
and s[i - 1] == "-"
and s[i - 2] == "("
&nbs***bsp;(i == 1 and s[i - 1] == "-")
):
pos = 1
else:
pos = 0
j = i
while j < len(s) and s[j].isdigit():
num = num * 10 + int(s[j])
j += 1
if pos == 1:
num_stack.append(-num)
op_stack.pop()
else:
num_stack.append(num)
i = j
elif c in "+-/*":
while op_stack and prior[op_stack[-1]] >= prior[c]:
tow_num()
op_stack.append(c)
i += 1
elif c == "(":
op_stack.append(c)
i += 1
elif c == ")":
while op_stack[-1] != "(":
tow_num()
op_stack.pop()
i += 1
while op_stack:
tow_num()
print(num_stack[-1])
def calc(s):
args = list()
temp = ''
pn = 0
pn_st = 0
for i in range(len(s)):
if s[i] == '(':
pn += 1
if pn == 1:
pn_st = i + 1
elif s[i] == ')':
pn -= 1
if pn == 0:
args.append(calc(s[pn_st:i]))
elif pn == 0: # 没有括号的情况
if s[i].isdigit():
temp += s[i]
if i == len(s) - 1:
args.append(int(temp))
temp = ''
elif not s[i + 1].isdigit():
args.append(int(temp))
temp = ''
else:
args.append(s[i])
ans1 = list()
op = ''
for i in range(len(args)):
if isinstance(args[i], int):
if op == '':
ans1.append(args[i])
elif op == '*':
ans1[-1] = ans1[-1] * args[i]
op = ''
elif op == '/':
ans1[-1] = ans1[-1] / args[i]
op = ''
elif args[i] == '*':
op = args[i]
elif args[i] == '/':
op = args[i]
elif args[i] == '+':
ans1.append(args[i])
elif args[i] == '-':
ans1.append(args[i])
ans = 0
op = ''
for i in range(len(ans1)):
if isinstance(ans1[i], int):
if op == '':
ans = ans1[i]
elif op == '+':
ans += ans1[i]
elif op == '-':
ans -= ans1[i]
elif ans1[i] == '+':
op = ans1[i]
elif ans1[i] == '-':
op = ans1[i]
return ans
line = input()
print(calc(line))