后缀表达式(算法)

求解具有优先级的表达式时,我们会选择前缀表达式和后缀表达式,这样就需要将中缀表达式转换成前缀或者后缀表达式,转换方式如下:
1、创建两个栈,数据栈和符号栈
2、遍历字符串
3、如果当前是数据,直接存入数据栈
4、如果当前是左括号,直接存入符号栈
5、如果当前是右括号,循环弹出符号栈进入数据栈,直到输出左括号为止
6、如果当前是其它符号,循环符号栈的栈顶优先级高于当前符号则弹出进入数据栈

实现代码如下:

# 后缀表达式

s = '1+2*(2+3)*5-2'

stack = []
nums = []
i = 0
n = len(s)

while i < n:
    w = s[i]
    print(w,stack)
    if w == '(':
        stack.append(w)
    elif w in '+-*':
        if w in '+-':
            while stack and stack[-1] == '*':
                nums.append(stack.pop())
            stack.append(w)
        else:
            stack.append(w)
    elif w == ')':
        while stack[-1] != '(':
            nums.append(stack.pop())
        stack.pop()
    else:
        cur = 0
        while i < n and s[i].isdigit():
            cur = cur * 10 + int(s[i])
            i += 1
        nums.append(cur)
        continue
    i += 1
while stack:
    nums.append(stack.pop())

i = 0
n = len(nums)
stack = []
while i < n:
    w = nums[i]
    if isinstance(w,int):
        stack.append(w)
        i += 1
    else:
        if w == '+':
            stack.append(stack.pop()+stack.pop())
        elif w == '-':
            stack.append(-stack.pop()+stack.pop())
        else:
            stack.append(stack.pop()*stack.pop())
        i += 1
print(stack)

你可能感兴趣的:(算法,python)