Inverse Polish expression evaluation Python vs golang

Time:2020-10-28

Stack has great advantages in some matching scenarios and is very computer-friendly

Question surface

Calculate the value of inverse Polish (suffix expression), integer division only retains the integer part

Operator contains only"+","-","*"and"/"The operands may be integers or other expressions

["20", "10", "+", "30", "*"] -> ((20 + 10) * 30) -> 900
["40", "130", "50", "/", "+"] -> (40 + (130 / 50)) -> 42

analysis

  • Encountered operands stack
  • When the operator takes the top two operands of the stack, the calculation result is put on the stack
  • Pay attention to the stack order, first in and then out, especially when calculating division and subtraction

Python solution

Short and sharp

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        st = []
        for v in tokens:
            if v in "+-*/":
                b, a = st.pop(),st.pop()
                if v == "+": st.append(a + b)
                if v == "-": st.append(a - b)
                if v == "*": st.append(a * b)
                if v == "/": st.append(int(a / b))
            else:
                st.append(int(v))
        return st[-1]

Or so with the insaneeval

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        st = []
        for v in tokens:
            if v in "+-*/":
                b,a = st.pop(),st.pop()
                st.append(eval("%d%s%d"%(a,v,b)))
            else:
                st.append(int(v))
        return int(st[-1])

Golang implementation

The rune type implicitly converts a string

import "strconv"
func evalRPN(tokens []string) int {
    st := []int{}
    for _,v := range tokens {
        if v == "+" || v == "-" || v == "*" || v == "/" {
            if len(st)< 2 {
                return 0
            }
            b := st[len(st)-1]
            st = st[:len(st)-1]
            a := st[len(st)-1]
            st = st[:len(st)-1]
            switch v {
                case "+": st = append(st, a+b)
                case "-": st = append(st, a-b)
                case "*": st = append(st, a*b)
                case "/": st = append(st, a/b)
            }
        }else{
            if num,err := strconv.Atoi(v); err == nil {
                st = append(st, num)
            }
        }
    }
    return st[len(st)-1]
}

performance

Submission time Submit results Running time Memory consumption language
A few seconds ago adopt 4 ms 4.1 MB Go
A few seconds ago adopt 44 ms 13.7 MB Python3

This work adoptsCC agreementThe author and the link to this article must be indicated in the reprint