(python) leetcode刷题——evaluate-reverse-polish-notation

版权声明:本文为博主原创文章,未经允许不得转载,如有问题,欢迎指正。 https://blog.csdn.net/qq_36107350/article/details/90177813

题目:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are+,-,,/. Each operand may be an integer or another expression.
Some examples:
[“2”, “1”, “+”, “3”, "
"] -> ((2 + 1) * 3) -> 9
[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6

解析:
典型的使用栈的例子,本科数据结构课程有讲。
1,遍历列表,建立空栈
2,遇到数字,将它入栈
3,遇到运算符,取栈内数字两次,得到的两个数进行对应运算符运算,将运算结果入栈
4,遍历完毕,取栈,得到最终结果

代码:

def prnval(a):
    stack = []
    for i in range(len(a)):
        if a[i] == '+' or a[i] == '-' or a[i] == '*' or a[i] == '/':
            x = stack.pop()
            y = stack.pop()
            if a[i] == '+':
                stack.append(x+y)
            elif a[i] == '-':
                stack.append(y-x)
            elif a[i] == '*':
                stack.append(x*y)
            else:
                stack.append(y//x)
        elif a[i] != None:
            stack.append(int(a[i]))
    return stack.pop()

全部代码:

def prnval(a):
    stack = []
    for i in range(len(a)):
        if a[i] == '+' or a[i] == '-' or a[i] == '*' or a[i] == '/':
            x = stack.pop()
            y = stack.pop()
            if a[i] == '+':
                stack.append(x+y)
            elif a[i] == '-':
                stack.append(y-x)
            elif a[i] == '*':
                stack.append(x*y)
            else:
                stack.append(y//x)
        elif a[i] != None:
            stack.append(int(a[i]))
    return stack.pop()

if __name__=='__main__':
    a = ["2","1","+","3","*"]
    b = ["4", "13", "5", "/", "+"]
    print(prnval(a),prnval(b)

猜你喜欢

转载自blog.csdn.net/qq_36107350/article/details/90177813