Skip to content

Instantly share code, notes, and snippets.

@Josephchinedu
Created April 9, 2022 12:57
Show Gist options
  • Save Josephchinedu/5d5be923d7effa98b02f580b6c7a1642 to your computer and use it in GitHub Desktop.
Save Josephchinedu/5d5be923d7effa98b02f580b6c7a1642 to your computer and use it in GitHub Desktop.
baseball game
# You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores.
# At the beginning of the game, you start with an empty record. You are given a list of strings ops, where ops[i] is the ith operation you must apply to the record and is one of the following:
# An integer x - Record a new score of x.
# "+" - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores.
# "D" - Record a new score that is double the previous score. It is guaranteed there will always be a previous score.
# "C" - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score.
########## Steps:
# loops through a list
# looks for the ones that are number and push them into a stack
# check if the next character loop is "C". if it is, pop your stack list
# check if the next character loop is "D". if it is, double the last element in the stack list
# check if the next character loop is "+". if it is, sum the recent last two stack and add them back to the stack
class Solution:
def isNumber(self, s):
s = s.strip()
try:
s = float(s)
return True
except:
return False
def calPoints(self, ops: List[str]) -> int:
score_history = []
for i in ops:
if self.isNumber(i):
score_history.append(int(i))
elif i == "C":
score_history.pop()
elif i == "D":
score_history.append(score_history[-1] * 2)
elif i == "+":
score_history.append(score_history[-1] + score_history[-2])
return sum(score_history)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment