Baseball Game in Python


Suppose we have a baseball game point recorder. We have a list of strings; each string can be one of the 4 following types −

  • Integer (one round's score) − Indicates the number of points we get in this round.
  • "+" (one round's score) − Indicates the points we get in this round are the sum of the last two valid round's points.
  • "D" (one round's score ) − Indicates the points we get in this round are the doubled data of the last valid round's points.
  • "C" (an operation, which isn't a round's score) − Indicates the last valid round's points we get were invalid and should be removed.

Note that each round's operation is permanent and could have an impact on the round before and the round after. We have to find the sum of the points we could get in all the rounds.

So, if the input is like ["5","2","C","D","+"], then the output will be 30. This is actually for

  • Round 1 − We could get 5 points. The sum is: 5.
  • Round 2 − We could get 2 points. The sum is: 7.
  • Operation 1 − The data of the round 2 was invalid. The sum is: 5.
  • Round 3 − We could get 10 points. The sum is: 15.
  • Round 4 − We could get 5 + 10 = 15 points. The sum is: 30.

To solve this, we will follow these steps −

  • stack := empty list
  • for each i in ops, do
    • if i is same as "+", then
      • first := stack[size of stack - 1], second := stack[size of stack - 2]
      • insert (first + second) into stack at the end
    • otherwise when i is same as "D", then
      • insert (last element of stack * 2) into stack at the end
    • otherwise when i is same as "C", then
      • delete last element from stack
    • otherwise,
      • insert i into stack at the end
  • return sum of all elements of stack

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def calPoints(self, ops):
      stack = []
      for i in ops:
         if i == "+":
            first, second = stack[len(stack) - 1],
            stack[len(stack) - 2]
            stack.append(first + second)
         elif i == "D":
            stack.append(stack[-1] * 2)
         elif i == "C":
            stack.pop()
         else:
            stack.append(int(i))
      return sum(stack)
ob = Solution()
print(ob.calPoints(["5","2","C","D","+"]))

Input

["5","2","C","D","+"]

Output

30

Updated on: 04-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements