lintcode算法-3 983 · 棒球游戏

题目描述:

现在你是棒球比赛分记录员。

给定一个字符串数组,每一个字符串可以是以下4种中的其中一个:

  1. 整数 (一个回合的分数): 直接表示这回合你得到的分数。
  2. "+" (一个回合的分数): 表示这回合你获得的分数为前两个 有效 分数之和。
  3. "D" (一个回合的分数): 表示这回合你得到的分数为你上一次获得的有效分数的两倍。
  4. "C" (一种操作,而非一个回合的分数): 表示你上回合的有效分数是无效的,需要移除。

每一轮的操作都是永久性的,可能会影响之前和之后的一轮。

你需要返回在所有回合中获得总分数。

按照自己的思路写了一下,虽然能够达到效果,但发现自己的解题思路稀烂,我的代码如下:

from typing import (
    List,
)

class Solution:
    """
    @param ops: the list of operations
    @return:  the sum of the points you could get in all the rounds
    """
    def cal_points(self, ops: List[str]) -> int:
        # Write your code here
        str_array = ops
        previous_one=0
        previous_two=0
        sum_num=0
        for i in range(0,len(str_array)):
            if str_array[i] == 'C':
                sum_num -= previous_one
                previous_one = previous_two
            elif str_array[i] == 'D':
                sum_num += (previous_one * 2)
                previous_two = (previous_one * 2)
            elif str_array[i] == '+':
                sum_num += previous_two + previous_one
            else:
                tmpInt = int(str_array[i])
                sum_num += tmpInt
                previous_two = previous_one
                previous_one = tmpInt
        return sum_num

ops = ["5","2","C","D","+"]
a=Solution()
result=a.cal_points(ops)
print(result)

妥妥的过程化,以及更没有用到List的特性, 然后按照官方的答案重写了一遍,如下

from typing import (
    List,
)

class Solution:
    """
    @param ops: the list of operations
    @return:  the sum of the points you could get in all the rounds
    """
    def cal_points(self, ops: List[str]) -> int:
        # Write your code here
        str_array = []
        for i in ops:
            if i == 'C':
                str_array.pop()
            elif i == 'D':
                str_array.append(str_array[len(str_array) - 1] * 2)
            elif i == '+':
                str_array.append(str_array[len(str_array) - 2]+str_array[len(str_array) - 1])
            else:
                str_array.append(int(i))
        return sum(str_array)

ops = ["5","-2","4","C","D","9","+","+"]
a=Solution()
result=a.cal_points(ops)
print(result)

这个明显优雅多了

1.利用list特性方法pop移除list中最后一个元素,符合C流程的条件

 2.利用list特性方法append将新分数更新进list,并且可以直接通过下标拿到符合D条件的list中存储的分数进行计算

3.利用Python自带的sum函数可以对元组或list进行迭代计算(真方便) 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值