题解 | #表达式求值#
表达式求值
http://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
exp_list = []
h_exp_list = []
stack_1 = []
stack_2 = []
def strtolist():
"""处理输入"""
r_exp = list(input())
for i in range(len(r_exp)):
if (r_exp[i] == '[') or (r_exp[i] == '{'):
r_exp[i] = '('
if (r_exp[i] == ']') or (r_exp[i] == '}'):
r_exp[i] = ')'
flag = 1
number = 0
for i in range(len(r_exp)):
# 对负数的处理,第一个数是负数和左括号后面有减号就是负数。
if (i == 0 and r_exp[i] == '-') or (r_exp[i - 1] == '(' and '-' == r_exp[i]):
flag = -1
elif '0' <= r_exp[i] <= '9':
number = number * 10 + int(r_exp[i])
if len(r_exp) == i+1 or r_exp[i+1] < '0' or r_exp[i+1] > '9' :
exp_list.append(flag * number)
number = 0
flag = 1
else:
exp_list.append(r_exp[i])
def process(ch):
"中缀表达式转后缀表达式"
if ('(' == ch): # 读到左括号时,将其压入堆栈中。
stack_1.append(ch)
# 遇到右括号时,右括号本身不入栈,从栈顶开始弹出操作符,放入输出流,直到遇到一个左括号为止,将这个左括号弹出,但是不放入输出流。
elif (')' == ch):
while True:
tmp = stack_1.pop()
if tmp != '(':
h_exp_list.append(tmp)
else:
break
elif '*' == ch or '/' == ch:
while True:
if 0 == len(stack_1):
stack_1.append(ch)
break
else:
tmp = stack_1.pop()
if (tmp == '*') or (tmp == '/'):
h_exp_list.append(tmp)
else:
stack_1.append(tmp)
stack_1.append(ch)
break
elif '+' == ch or '-' == ch:
while True:
if 0 == len(stack_1):
stack_1.append(ch)
break
else:
tmp = stack_1.pop()
if '(' != tmp:
h_exp_list.append(tmp)
else:
stack_1.append(tmp)
stack_1.append(ch)
break
else:
h_exp_list.append(ch)
strtolist()
for ch in exp_list:
process(ch)
L = len(stack_1)
while L:
h_exp_list.append(stack_1.pop())
L -= 1
def calcuValue(h_exp_list):
for i in range(len(h_exp_list)):
if h_exp_list[i] in ['+', '-', '*', '/']:
op2 = stack_2.pop()
op1 = stack_2.pop()
if h_exp_list[i] == '+':
res = op1 + op2
elif h_exp_list[i] == '-':
res = op1 - op2
elif h_exp_list[i] == '*':
res = op1 * op2
elif h_exp_list[i] == '/':
res = op1 / op2
stack_2.append(res)
else:
stack_2.append(h_exp_list[i])
calcuValue(h_exp_list)
result_list = str(stack_2[0]).split('.')
if result_list[-1] == '0':
print(result_list[0])
else:
print(stack_2[0])
PS:这个题目的答案是复用的四则运算那道题的。 PPS:关于详细的思路解法,可以看这里:https://blog.csdn.net/zy010101/article/details/82728726