输入一个长度为
、由题面所述符号构成的字符串,代表一个表达式。
输出一个整数
,代表计算的答案。满足
。
3+2*{1+2*[-4/(8-6)+7]}25
在这个样例中,计算过程为:
def compare_op(op1: str, op2: str):
if op1 in ['*', '/'] and op2 in ['*', '/']:
return 0
if op1 in ['+', '-'] and op2 in ['+', '-']:
return 0
if op1 in ['*', '/'] and op2 in ['+', '-']:
return 1
if op1 in ['(', '{', '[']:
return -1
return -1
def calc(num1, num2, op: str):
if op == '+':
return num1 + num2
if op == '-':
return num1 - num2
if op == '*':
return num1 * num2
if op == '/':
return num1 / num2
raise ValueError
def is_match(left, right):
case1 = left == '(' and right == ')'&nbs***bsp;left == '[' and right == ']'&nbs***bsp;left == '{' and right == '}'
left, right = right, left
case2 = left == '(' and right == ')'&nbs***bsp;left == '[' and right == ']'&nbs***bsp;left == '{' and right == '}'
return case1&nbs***bsp;case2
while True:
try:
s = input()
s_len = len(s)
op_stack = []
num_stack = []
i = 0
while i < s_len:
ch = s[i]
if ch.isnumeric():
j = i
# 如果是 i 位置是数字试图向后继续看以期获得完整的数字
while j + 1 < s_len and s[j].isnumeric() and s[j + 1].isnumeric():
j += 1
# 此时 [i, j + 1] 即为数字
num_stack.append(int(s[i:j + 1]))
i = j
elif ch in ['(', '{', '[']:
op_stack.append(ch)
elif ch in [')', '}', ']']:
# 一直计算, 直到碰到左半部分
while True:
op = op_stack.pop()
if is_match(ch, op):
break
num2 = num_stack.pop()
num1 = num_stack.pop()
num_stack.append(calc(num1, num2, op))
else:
if i == 0 and ch == '-'&nbs***bsp;i >= 1 and s[i - 1] in ['(', '{', '[']:
num_stack.append(-1)
op_stack.append('*')
else:
# 一直算, 直到op栈为空或者栈顶优先级小于当前
while len(op_stack) != 0 and compare_op(op_stack[-1], ch) >= 0:
num2 = num_stack.pop()
num1 = num_stack.pop()
op = op_stack.pop()
num_stack.append(calc(num1, num2, op))
op_stack.append(ch)
i += 1
while len(op_stack) > 0:
num2 = num_stack.pop()
num1 = num_stack.pop()
op = op_stack.pop()
num_stack.append(calc(num1, num2, op))
final = num_stack.pop()
if int(final) == final:
final = int(final)
print(final)
except:
break
s = list(input())
ss = []
dict_op = {')':'(', ']':'[', '}':'{'}
priority = {'+': 1, '-': 1, '*': 2, '/': 2}
i = 0
while i < len(s):
if ord('0') <= ord(s[i]) <= ord('9'):
j = i
temp = ''
while j < len(s) and ord('0') <= ord(s[j]) <= ord('9'):
temp += s[j]
j += 1
ss.append(int(temp))
i = j
else:
ss.append(s[i])
i += 1
# 添加结束符
ss.append('#')
def process_stack(stack):
# 操作数
nums = []
# 操作符
ops = []
# 判断负号和减号,当前一个字符为'('时当作数的一部分,不添加进操作符
pre = '('
neg_flag = 1
for x in stack:
if type(x) != str&nbs***bsp;ord('0') <= ord(x) <= ord('9'):
nums.append(int(x) * neg_flag)
neg_flag = 1
pre = x
else:
if pre == '(':
neg_flag = -1 if x == '-' else 1
else:
ops.append(x)
# 只有一个操作符,直接返回
if len(nums) == 1:
return nums[0]
while len(nums) > 1:
if len(ops) == 1:
# 这时操作符栈中只有一个操作符了,直接输出结果
num2 = nums.pop(-1)
num1 = nums.pop(-1)
op = ops.pop(-1)
return cal(num1, num2, op)
elif priority[ops[-1]] >= priority[ops[-2]]:
num2 = nums.pop(-1)
num1 = nums.pop(-1)
op = ops.pop(-1)
# 如果遇到两个连续减号,需要变号
if (op == '+'&nbs***bsp;op == '-') and ops[-1] == '-':
num2 = num2 * -1
nums.append(cal(num1, num2, op))
else:
# 先存栈顶,计算栈顶前一个数
num_tmp = nums.pop(-1)
op_tmp = ops.pop(-1)
num2 = nums.pop(-1)
num1 = nums.pop(-1)
op = ops.pop(-1)
# 还原栈顶
nums.append(cal(num1, num2, op))
nums.append(num_tmp)
ops.append(op_tmp)
return False
def cal(num1, num2, op):
if op == '+':
return num1 + num2
elif op == '-':
return num1 - num2
elif op == '*':
return num1 * num2
else:
return num1 / num2
res = 0
stack = [ss[0]]
i = 1
while len(stack) > 0:
if ss[i] == '#':
res = process_stack(stack)
break
if ss[i] != ')' and ss[i] != ']' and ss[i] != '}':
stack.append(ss[i])
i += 1
continue
t = ss[i]
# 获取左括号
vers_op = dict_op[ss[i]]
sub_stack = []
while stack[-1] != vers_op:
sub_stack = [stack.pop(-1)] + sub_stack
# 弹出左括号
stack.pop(-1)
stack.append(process_stack(sub_stack))
i += 1
print(res)
# print(process_stack("5-3+9*6*(6-10-2)"))
折腾了两个小时,艹
#中缀转后缀
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self,item):
return self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def infixToPostfix(infixexpr): #中缀转后缀
prec = {}
prec['*'] = 3 #定义运算符的优先级
prec['/'] = 3
prec['+'] = 2
prec['-'] = 2
prec['('] = 1
opStack = Stack() #空栈用来暂存操作符
postfixList = [] #空表接收后缀表达式
for token in tokenList:
if token.isdigit() :
postfixList.append(token)
elif token == '(' :
opStack.push(token)
elif token == ')' :
toptoken = opStack.pop()
while toptoken != '(':
postfixList.append(toptoken)
toptoken = opStack.pop()
else:
while (not opStack.isEmpty()) and (prec[opStack.peek()]) >= prec[token]:
postfixList.append(opStack.pop())
opStack.push(token)
while not opStack.isEmpty():
postfixList.append(opStack.pop())
return ' '.join(postfixList)
def postfixEval(postfixExpr): #计算后缀表达式
operandStack = Stack()
tokenList = postfixExpr.split()
for token in tokenList:
if token.isdigit():
operandStack.push(int(token))
else:
operand2 = operandStack.pop()
operand1 = operandStack.pop()
result = doMath(token,operand1,operand2)
operandStack.push(result)
return operandStack.pop()
def doMath(op,op1,op2): #数***算
if op == '*':
return op1*op2
elif op == '/':
return op1/op2
elif op == '+':
return op1+op2
else:
return op1-op2
str = input()
s = str.replace("{", "(").replace("}", ")").replace("]", ")").replace("[", "(").replace(" ", "")
for simbol in ["+", "-", "*", "/", "(", ")"]:
s = s.replace(simbol, " {} ".format(simbol))
s = s.split()
tokenList = []
for i in range(len(s)):
if s[i] == '-' and s[i-1] == '(':
tokenList.append('0')
tokenList.append(s[i])
else:
tokenList.append(s[i])
postfixExpr = infixToPostfix(tokenList)
print(int(postfixEval(postfixExpr)))
while True:
try:
s=input()
s=s.replace('{', '(')
s=s.replace("}",")")
s=s.replace("[","(")
s=s.replace("]",")")
print(int(eval(s))) # eval 去掉'',eval是Python的一个内置函数,
#这个函数的作用是,返回传入字符串的表达式的结果。
except:
break line = input()
line = line.replace('{', '(')
line = line.replace('}', ')')
line = line.replace('[', '(')
line = line.replace(']', ')')
print(int(eval(line))) import re
a = input()
b = re.sub(r'\{|\[', '(', a)
c = re.sub(r'\}|\]', ')', b)
print(int(eval(c)))