Baseball Game in Python

A baseball game point recorder tracks scores using operations on a stack. We have a list of strings where each string represents either a score or an operation that modifies previous scores.

Game Rules

The four types of operations are ?

  • Integer − Indicates the number of points scored in this round
  • "+" − Points are the sum of the last two valid rounds
  • "D" − Points are double the last valid round's points
  • "C" − Cancel the last valid round (remove from record)

Example Walkthrough

For input ["5","2","C","D","+"], the process works as follows ?

  • Round 1: Score 5 points. Total: 5
  • Round 2: Score 2 points. Total: 7
  • Operation C: Cancel round 2. Total: 5
  • Round 3 (D): Double last valid (5 × 2 = 10). Total: 15
  • Round 4 (+): Sum last two valid (5 + 10 = 15). Total: 30

Algorithm

We use a stack to track valid scores and process each operation ?

def calPoints(ops):
    stack = []
    
    for operation in ops:
        if operation == "+":
            # Sum of last two valid scores
            first = stack[-1]
            second = stack[-2]
            stack.append(first + second)
        elif operation == "D":
            # Double the last valid score
            stack.append(stack[-1] * 2)
        elif operation == "C":
            # Cancel last valid score
            stack.pop()
        else:
            # Add integer score
            stack.append(int(operation))
    
    return sum(stack)

# Test the function
operations = ["5", "2", "C", "D", "+"]
result = calPoints(operations)
print(f"Operations: {operations}")
print(f"Final score: {result}")
Operations: ['5', '2', 'C', 'D', '+']
Final score: 30

Step-by-Step Execution

Let's trace through the algorithm with our example ?

def calPoints_with_trace(ops):
    stack = []
    print("Step-by-step execution:")
    
    for i, operation in enumerate(ops):
        print(f"Step {i+1}: Operation '{operation}'")
        
        if operation == "+":
            first = stack[-1]
            second = stack[-2]
            new_score = first + second
            stack.append(new_score)
            print(f"  Add sum of last two: {second} + {first} = {new_score}")
        elif operation == "D":
            new_score = stack[-1] * 2
            stack.append(new_score)
            print(f"  Double last score: {stack[-2]} × 2 = {new_score}")
        elif operation == "C":
            removed = stack.pop()
            print(f"  Cancel last score: removed {removed}")
        else:
            stack.append(int(operation))
            print(f"  Add score: {operation}")
        
        print(f"  Stack: {stack}")
        print()
    
    total = sum(stack)
    print(f"Final total: {total}")
    return total

# Execute with trace
calPoints_with_trace(["5", "2", "C", "D", "+"])
Step-by-step execution:
Step 1: Operation '5'
  Add score: 5
  Stack: [5]

Step 2: Operation '2'
  Add score: 2
  Stack: [5, 2]

Step 3: Operation 'C'
  Cancel last score: removed 2
  Stack: [5]

Step 4: Operation 'D'
  Double last score: 5 × 2 = 10
  Stack: [5, 10]

Step 5: Operation '+'
  Add sum of last two: 5 + 10 = 15
  Stack: [5, 10, 15]

Final total: 30

Key Points

  • Stack operations ensure we always work with valid scores
  • Each operation permanently affects the game state
  • The "+" operation requires at least two previous scores
  • Time complexity: O(n), Space complexity: O(n)

Conclusion

The baseball game recorder uses a stack-based approach to handle score operations efficiently. Each operation modifies the stack of valid scores, and the final sum represents the total points earned.

Updated on: 2026-03-25T08:46:21+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements