baseball game records

topic:

You are now the scorer for a special baseball game. The game consists of several rounds, and the scores of past rounds may affect the scores of later rounds.

When the game starts, the record is blank. You will get a string list ops that records operations, where ops[i] is the i-th operation you need to record, and ops follows the following rules:

    Integer x - indicates the new score of this round x
    "+" - indicates that the new score of this round is the sum of the previous two scores. The question data guarantees that there are always two valid preceding scores when recording this operation.
    "D" - Indicates that the new score obtained in this round is double the previous score. The question data guarantees that there is always a valid preceding score when recording this operation.
    "C" - Indicates that the previous score was invalid and removed from the record. The question data guarantees that there is always a valid preceding score when recording this operation.

Please return the sum of all scores in the record.

Source: LeetCode
Link: https://leetcode.cn/problems/baseball-game

Example:

Input: ops = ["5","-2","4","C","D","9","+","+"] Output: 27 Explanation: "5" - add 5
to
the
record , record is now [5]
"-2" - record plus -2, record is now [5, -2]
"4" - record plus 4, record is now [5, -2, 4]
"C" - make The record from the previous score is invalidated and removed, the record is now [5, -2]
"D" - record plus 2 * -2 = -4, the record is now [5, -2, -4]
"9" - record plus 9, record is now [5, -2, -4, 9]
"+" - record plus -4 + 9 = 5, record is now [5, -2, -4, 9, 5]
"+ "- record plus 9 + 5 = 14, record is now [5, -2, -4, 9, 5, 14]
sum of all scores 5 + -2 + -4 + 9 + 5 + 14 = 27

code:

class Solution(object):
    def calPoints(self, operations):
        """
        :type operations: List[str]
        :rtype: int
        """
        a=[]
        sum1=0
        for i in operations:
            if i.isdigit():
                a.append(int(i))
            elif i=='C':
                a.remove(a[len(a)-1])
            elif i=='D':
                a.append(2*a[len(a)-1])
            elif i=='+':
                a.append(a[len(a)-1]+a[len(a)-2])
            else:
                a.append(int(i))
        sum1+=sum(a)
        return sum1

Guess you like

Origin blog.csdn.net/Tinyfacture/article/details/131962558