输入一个长度为
、由题面所述符号构成的字符串,代表一个表达式。
输出一个整数
,代表计算的答案。满足
。
3+2*{1+2*[-4/(8-6)+7]}25
在这个样例中,计算过程为:
print(eval(input()))
while True:
try:
exp = input().replace('{', '(').replace('}', ')').replace('[', '(').replace(']', ')')
result = eval(exp)
print(int(result))
except EOFError:
break import operator
OPS = {'+': 0, '-': 0, '*' : 1, '/': 1, '{': 2, '[': 3, '(':4 }
OPEN_OPS = {'{', '[', '('}
CLOSE_OPS = {'}': '{', ']':'[', ')':'('}
op = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}
def tokenize(expression):
token = ""
for c in expression:
if not c.isdigit():
if token != "":
yield token
token = ""
yield c
else:
token += c
if token:
yield token
def infix_to_postfix(expression: str):
op_stack = []
res = []
for c in tokenize(expression):
# 1. 如果是数字直接 append res
if c.isdigit():
res.append(c)
# 2. 如果是操作符
elif c in OPS:
# 2.1 如果栈为空 或 操作符为开括号 或 等级大于栈顶操等级 或 栈顶为开括号, 加入op栈
if len(op_stack) == 0&nbs***bsp;c in OPEN_OPS&nbs***bsp;op_stack[-1] in OPEN_OPS&nbs***bsp;OPS[c] > OPS[op_stack[-1]]:
op_stack.append(c)
# 2.2 如果操作符等级小于栈顶操作符等级, 先出栈**栈, 直到栈顶大于操作符等级为止
else:
while len(op_stack) > 0 and op_stack[-1] not in OPEN_OPS and OPS[c] <= OPS[op_stack[-1]]:
res.append(op_stack[-1])
op_stack.pop()
op_stack.append(c)
# 3. 如果是结束括号
elif c in CLOSE_OPS:
# 持续出栈, 直到遇到匹配的开始括号
while len(op_stack) > 0 and op_stack[-1] != CLOSE_OPS[c]:
res.append(op_stack[-1])
op_stack.pop()
if len(op_stack) > 0 and op_stack[-1] == CLOSE_OPS[c]:
op_stack.pop()
while len(op_stack) > 0:
res.append(op_stack[-1])
op_stack.pop()
return res
def evaluate(postfix: list):
value_stack = []
num1, num2 = None, None
for token in postfix:
if token.isdigit():
if num1 is None:
num1 = int(token)
continue
if num2 is None:
num2 = int(token)
continue
value_stack.append(num1)
num1, num2 = num2, int(token)
elif token in op:
if num1 is not None and num2 is None and len(value_stack) > 0:
num1, num2 = value_stack.pop(), num1
if num1 is not None and num2 is not None:
num1 = op[token](num1, num2)
num2 = None
continue
return num1 import collections
def cat(exe_in):
limao = exe_in.replace('{', '(').replace('}', ')').replace('[', '(').replace(']', ')')
puc = [i for i in limao.strip()]
# print(puc)
# 如果碰到负数,在负数前加0
puc_copy = []
tmp = [] # 临时存储数字以合并个位数以上的数字
if puc[0] == '-':
puc_copy.append('0')
puc_copy.append('-')
elif puc[0].isdigit():
tmp.append(puc[0])
else:
puc_copy.append(puc[0])
# 十位数以上数字字符串合并
for i in range(1, len(puc)+1):
# print(puc[i])
if i < len(puc):
if puc[i] == '-' and puc[i - 1] == '(':
puc_copy.append('0')
puc_copy.append('-')
elif puc[i].isdigit():
tmp.append(puc[i])
elif tmp:
# print(tmp)
combine = ''.join(tmp)
puc_copy.append(combine)
puc_copy.append(puc[i])
tmp = []
else:
puc_copy.append(puc[i])
else:
if tmp: # 表达式末尾的数字字符串
combine = ''.join(tmp)
puc_copy.append(combine)
return puc_copy
def exe_transfer(exep):
# 创建字典进行优先级比较
coll_dict = collections.OrderedDict()
coll_dict = {'+': 5, '-': 5, '*': 4, '/': 4, '{': 3, '}': 3, '[': 2, ']': 2, '(': 1, ')': 1}
# 中缀表达式转化为前缀表达式
# 运算符栈S1【栈顶优先级更高】 + 存储中间结果栈S2【从右往左扫描中缀表达式数字】
exep.reverse()
S1, S2 = [], []
for i in exep:
# print('-----------')
# print(i)
# print(S1)
# print(S2)
# 判断字符串是否为数字
if i.isdigit():
S2.append(int(i))
# 操作符
else:
if S1 == []&nbs***bsp;S1 == ')': # 如果S1为空或者右括号直接入栈
S1.append(i)
elif S1[-1] == ')': # 如果S1栈顶为右括号直接入栈
S1.append(i)
elif i == '(': # 左括号带走右括号,并将他们之间的值推入S2
for j in range(len(S1) - 1, -1, -1):
if S1[j] != ')':
S2.append(S1[j])
S1.pop()
else:
S1.pop()
break
elif coll_dict[i] <= coll_dict[S1[-1]]: # 如果即将入栈的优先级较高直接入栈
S1.append(i)
# 有点小问题
else: # 如果即将入栈的优先级较低
S2.append(S1[-1])
S1.pop()
for j in range(len(S1)+1):
if S1 == []:
S1.append(i)
break
if S1[-1] == ')':
S1.append(i)
break
if coll_dict[i] > coll_dict[S1[-1]]:
S2.append(S1[-1])
S1.pop()
else:
S1.append(i)
break
# S1剩余部分
for k in range(len(S1)):
S2.append(S1[-1])
S1.pop()
# 返回前缀表达式
return S2
# S2计算函数
# 从右往左扫,碰到数字就入栈,碰到操作符就弹出栈顶的两个元素进行计算然后将计算结果入栈
def exe_cacul(prefix):
S3 = []
for i in prefix:
# print(i)
if i == '+'&nbs***bsp;i == '-'&nbs***bsp;i == '*'&nbs***bsp;i == '/':
if i == '+':
answer = S3[-1]+S3[-2]
elif i == '-':
answer = S3[-1] - S3[-2]
elif i == '*':
answer = S3[-1] * S3[-2]
else:
answer = S3[-1] / S3[-2]
S3.pop()
S3.pop()
S3.append(answer)
else: # 数字直接入栈
S3.append(i)
# print(S3)
return S3[0]
if __name__ == '__main__':
exe_in = input()
puc_copy = cat(exe_in)
# print(puc_copy)
prefix = exe_transfer(puc_copy)
# print(prefix)
print(int(exe_cacul(prefix)))
四则运算
看了一些解法后,自己实现了一遍
class Solution:
def houxu(self, s: str):
s.replace('[', '(')
s.replace('{', '(')
s.replace(']', ')')
s.replace('}', ')')
map_dict = {
"*": 3,
"/": 3,
"+": 2,
"-": 2,
"(": 1
}
digi_stack = []
sigh_stack = []
flag = 1
j = -1
for i in range(len(s)):
if i < j:
continue
if s[i].isdigit():
j = i
while j < len(s) and s[j].isdigit():
j += 1
digi_stack.append(flag * int(s[i:j]))
elif s[i] == '(':
sigh_stack.append(s[i])
elif s[i] in ['+', "-", "*", "/"]:
if s[i] == "-":
if i == 0 or s[i - 1] == "(" or s[i - 1] in ['+', "-", "*", "/"]:
flag = -1
continue
flag = 1
while sigh_stack and map_dict[sigh_stack[-1]] >= map_dict[s[i]]:
digi_stack.append(sigh_stack.pop())
sigh_stack.append(s[i])
elif s[i] == ")":
temp = sigh_stack.pop()
while temp != "(":
digi_stack.append(temp)
temp = sigh_stack.pop()
while sigh_stack:
digi_stack.append(sigh_stack.pop())
# res = " ".join(digi_stack)
return digi_stack
def calcute(self, a, b, c):
if c == "+": return a + b
if c == "-": return a - b
if c == "*": return a * b
if c == "/": return a // b
def calcuteResults(self, s):
digi_stack = self.houxu(s)
di_stack = []
for x in digi_stack:
if isinstance(x, int):
di_stack.append(x)
else:
b = di_stack.pop()
a = di_stack.pop()
di_stack.append(self.calcute(a, b, x))
print(di_stack[0])
s = input()
solu = Solution()
solu.calcuteResults(s) #!usr/bin/env python while 1: try: s = input() print s except: break
def pri(a):
if a == '(':
return 1
elif a == '+' or a == '-':
return 2
elif a == '*' or a == '/':
return 3
def cal(a,b,c):
if c == '-':
return int(a) - int(b)
elif c == '+':
return int(a) + int(b)
elif c == '*':
return int(a) * int(b)
elif c == '/':
return int(a)//int(b)
while True:
try:
s = input().strip()
data = []
yunsuan = []
s = s.replace('[','(')
s = s.replace('{','(')
s = s.replace('}',')')
s = s.replace(']',')')
i = 0
while i < len(s):
if s[i].isdigit(): #处理数字
j = i
while j < len(s) and s[j].isdigit() :
j = j + 1
data.append(s[i:j])
i = j
elif s[i] in ['+','-','*','/']:
if s[i] == '-': #处理负数的情况,在-前面加上0
if i==0 or not s[i-1].isdigit() and s[i-1]!=')':
s = list(s)
s.insert(i,'0')
s = ''.join(s)
continue
if not yunsuan:
yunsuan.append(s[i])
else:
if pri(s[i]) > pri(yunsuan[-1]):
yunsuan.append(s[i])
else:
while yunsuan and pri(s[i]) <= pri(yunsuan[-1]):
sym = yunsuan.pop()
data.append(sym)
yunsuan.append(s[i])
i = i+ 1
else:
if s[i] == '(':
yunsuan.append(s[i])
else:
while yunsuan[-1] != '(':
data.append(yunsuan.pop())
yunsuan.pop()
i = i + 1
while yunsuan:
data.append(yunsuan.pop())
#print(data)
j = 0
while len(data) != 1:
try:
fl = int(data[j])
j += 1
except:
t1 = data.pop(j)
t2 = data.pop(j-1)
data[j-2] = str(cal(data[j-2],t2,t1))
j = j - 1
print(data[0])
except:
break