Skip to main content

Reverse Polish Notation

import math
const operations = ["+", "-", "*", "/"]
func evalReversePolishNotation(input: Array<String>): Number {    var stack = []
    for (var i = 0; i < input.length; i += 1) {        const value = input.get(i)
        if (!operations.contains(value)) stack.push(value.number())        else {            const b = stack.pop()            const a = stack.pop()
            if (value == "+") stack.push(a + b)            elif (value == "-") stack.push(a - b)            elif (value == "*") stack.push(a * b)            else stack.push(math.floor(a / b))        }    }        return stack.get(0)}
print(evalReversePolishNotation(["2","1","+","3","*"])) # 9print(evalReversePolishNotation(["4","13","5","/","+"])) # 6

This function evaluates a reverse polish notation expression. It takes an input of an array with type string, and outputs the evaluated expression as a number.