Extensible Python, No "if...else..."


  • 0
    OP = {
        '+': lambda a, b: a + b,
        '-': lambda a, b: a - b,
        '*': lambda a, b: a * b,
        '/': lambda a, b: int(float(a) / b)
    }
    
    
    class Solution(object):
        def evalRPN(self, tokens):
            """
            :type tokens: List[str]
            :rtype: int
            """
            stack = []
            for token in tokens:
                try:
                    num = int(token)
                    stack.append(num)
                except ValueError:
                    if token not in OP:
                        raise Exception("invalid operator")
                    if len(stack) < 2:
                        raise Exception("invalid numbers")
                    b = stack.pop()
                    a = stack.pop()
                    num = OP[token](a, b)
                    stack.append(num)
            if len(stack) != 1:
                raise Exception("invalid numbers")
            return stack.pop()
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.