题目描述:
现在你是棒球比赛分记录员。
给定一个字符串数组,每一个字符串可以是以下4种中的其中一个:
整数
(一个回合的分数): 直接表示这回合你得到的分数。"+"
(一个回合的分数): 表示这回合你获得的分数为前两个有效
分数之和。"D"
(一个回合的分数): 表示这回合你得到的分数为你上一次获得的有效
分数的两倍。"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进行迭代计算(真方便)