4.8-4.9 练手

Leetcode 150. Evaluate Reverse Polish Notation

第一次提交: faster than 26%+ 暴风哭泣

import math
class Solution(object):
    def opProcess(self, op, num1 , num2):
        if op == 0:
            return num1 + num2
        if op == 1:
            return num2 - num1
        if op == 2:
            return num1 * num2
        if op == 3:
            if num2 / num1 < 0:
                return int(math.ceil(float(num2)/num1))
            else:
                return int(num2 // num1)
    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        if len(tokens) == 1:
            return int(tokens[0])
        op = "+-*/"
        result = 0
        numStack = []
        for i in tokens:
            if i not in op:
                numStack.append(int(i))
            else:
                print(len(numStack))
                result = self.opProcess(op.find(i), numStack.pop(),numStack.pop())
                numStack.append(result)
              
        return result

4.9号的时候看了 Discuss 里面的答案:

关于如何处理趋向0可以不用math包里面的函数:

 stack = []
    for t in tokens:
        if t not in ["+", "-", "*", "/"]:
            stack.append(int(t))
        else:
            r, l = stack.pop(), stack.pop()
            if t == "+":
                stack.append(l+r)
            elif t == "-":
                stack.append(l-r)
            elif t == "*":
                stack.append(l*r)
            else:
                # here take care of the case like "1/-22",
                # in Python 2.x, it returns -1, while in 
                # Leetcode it should return 0
                if l*r < 0 and l % r != 0:
                    stack.append(l/r+1)
                else:
                    stack.append(l/r)
    return stack.pop()

然后速度提高了 5%的样子(手动再见

2.一款非常elegant的代码,定义符号的表示的方程真心好酷,要学习一下lambda表达式

class Solution:
    # @param {string[]} tokens
    # @return {integer}
    def __init__(self):
        self.operators = {
            '+': lambda y, x: x + y,
            '-': lambda y, x: x - y,
            '*': lambda y, x: x * y,
            '/': lambda y, x: int(operator.truediv(x, y))
        }

    def evalRPN(self, tokens):
        if not tokens:
            return 0

        stack = []

        for token in tokens:
            if token in self.operators:
                stack.append(self.operators[token](stack.pop(), stack.pop()))
            else:
                stack.append(int(token))

        return stack[0]

官方的答案:(趋向0 那边的处理也非常巧妙)

class Solution(object):
    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        stack = []
        
        operators = set(["+", "-", "*", "/"])
        for token in tokens:
            if token in operators:
                num2 = stack.pop()
                num1 = stack.pop()
                if token == "+":
                    stack.append(num1+num2)
                elif token == "-":
                    stack.append(num1-num2)
                elif token == "*":
                    stack.append(num1*num2)
                else:
                    stack.append(abs(num1) // abs(num2) * (-1 if num1 * num2 < 0 else 1))
                    
            else:
                stack.append(int(token))
        
        return stack[0]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值