一个后缀转换为中缀表达式的问题
将转换后的后缀表达式装换为中缀表达式,形式要稍微改变
例如 ab+变为 (a+b),abc+-变为(a-(b+c))
求大神给个想法吧,我想了很久了,要不就是大麻烦要不就是不可行
[解决办法]
先把中缀转后缀搞清楚,这个应该不难,词法分析略过,只提供思路
def convert(s):
s = s.split(' ')
stack = []
operators = ['-','+','*','/']
while s:
stack.append(s.pop(0))
if len(stack)>=3 and stack[-1] in operators and stack[-2] not in operators and stack[-3] not in operators:
stack[-3:] = ['('+' '.join((stack[-3],stack[-1],stack[-2]))+')']
return stack[0]
print(convert('a b +'))
print(convert('a b c + -'))
result
(a + b)
(a - (b + c))