Replay Tennis Game Commands and Report Scores
Data Structure DesignAuto-graded · 14 test casesLast updated
Simulate a single tennis game from a command log, tracking points, deuce, advantage and the winner, and return each score query's text.
You are given a log of commands that drive a single game of tennis between two players, "Player A" and "Player B". Replay the log and produce one output entry per command.
Commands
Command i is commands[i], and its arguments are params[i] (a list of strings).
"TennisMatch": start a fresh game with both players at zero points and no winner.params[i]is empty. OutputNone."point_won_by": the player named inparams[i][0]wins a point. OutputNone."score": report the current score.params[i]is empty. Output the score text described below.
Any other command name must raise a ValueError.
Scoring rules
Track how many points each player has won in the current game.
- The first four points for a player are called
Love,15,30,40(0, 1, 2, 3 points). - A player wins the game by having at least 4 points and leading the opponent by at least 2 points.
- Once a player has won, the game is over. Any later
point_won_bycommands are ignored, with no change to the score and no error, until a new"TennisMatch"command resets the game.
Score text
For a "score" command, output exactly one of the following, checked in this order:
- If the game has been won:
"Game "followed by the winner's name, for example"Game Player A". - Else, if both players have at least 3 points:
- equal points:
"Deuce" - otherwise:
"Advantage "followed by the name of the player who is ahead, for example"Advantage Player B".
- equal points:
- Otherwise: the call for Player A, a hyphen, then the call for Player B, for example
"30-Love","15-15","Love-Love".
Note that 4–3 is Advantage, not a win, and a tie below 40 (such as 15–15 or 30–30) is shown as numbers, not Deuce. Long deuce battles can run on indefinitely (for example 10–10 is still Deuce).
Task
Return a list with one entry per command, in order: None for "TennisMatch" and "point_won_by", and the score string for "score".
Constraints
len(commands) == len(params).- Player names in
point_won_byare always exactly"Player A"or"Player B". - Only a single game is modelled, with no sets or matches.
- A game may be reset by additional
"TennisMatch"commands in the same log.
Examples
Example 1
Input: replay_tennis_game(['TennisMatch', 'point_won_by', 'point_won_by', 'score'], [[], ['Player A'], ['Player A'], []])
Output: [None, None, None, '30-Love']
Example 2
Input: replay_tennis_game(['TennisMatch', 'point_won_by', 'point_won_by', 'point_won_by', 'point_won_by', 'point_won_by', 'point_won_by', 'score', 'point_won_by', 'score'], [[], ['Player A'], ['Player A'], ['Player A'], ['Player B'], ['Player B'], ['Player B'], [], ['Player B'], []])
Output: [None, None, None, None, None, None, None, 'Deuce', None, 'Advantage Player B']
Hints
Hint 1
Store only two integers, the points won by each player, and compute the displayed text from them whenever a score is requested.
Hint 2
Check conditions in a fixed order when formatting: game won first, then the both-at-least-3 zone (Deuce or Advantage), then the plain Love/15/30/40 lookup.
Hint 3
Winning needs at least 4 points and a lead of 2, so 4-3 is only Advantage. Remember to ignore points after the game is decided and to reset on a new TennisMatch command.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep the state as two integers: the number of points each player has won in the current game. Never store display strings such as "15" or "Advantage" as state. Every score the game can show is a pure function of the two counts.
Process the commands in order:
TennisMatchresets both counts to 0 and clears the winner.point_won_bydoes nothing if a winner already exists. Otherwise it increments that player's count and checks whether that player now has at least 4 points and leads by at least 2. If so, that player is recorded as the winner.scoreformats the counts in a fixed order:- A winner exists:
"Game <winner>". - Both counts are at least 3:
"Deuce"if they are equal, otherwise"Advantage"plus the leader. - Otherwise: look up each count in
["Love", "15", "30", "40"]and join with a hyphen.
- A winner exists:
Why it is correct
- While neither player has won and not both have 3 points, both counts are at most 3, so the lookup table is always in range. A count of 4 with no win implies the opponent has at least 3, which is handled by the deuce branch.
- From a tie
n-nwithn >= 3, one point gives a lead of 1, which is Advantage. If the leader loses the next point, the counts tie again, so Deuce returns naturally without any special transition code. - If the leader wins from Advantage, the lead becomes 2 with at least 4 points, which triggers the win condition. A player reaching 4 while the opponent has 2 or fewer also has a lead of 2 or more.
- Order of checks ensures each state matches exactly one branch, and 4-3 is correctly Advantage because the lead is only 1.
Complexity
- Time: O(n) for n commands, with O(1) work per command.
- Space: O(n) for the output list, plus O(1) game state.
Reference solution
from typing import List, Optional
def replay_tennis_game(commands: List[str], params: List[List[str]]) -> List[Optional[str]]:
calls = ["Love", "15", "30", "40"]
index = {"Player A": 0, "Player B": 1}
pts = [0, 0]
winner = None
out: List[Optional[str]] = []
for cmd, args in zip(commands, params):
if cmd == "TennisMatch":
pts = [0, 0]
winner = None
out.append(None)
elif cmd == "point_won_by":
if winner is None:
p = index[args[0]]
pts[p] += 1
if pts[p] >= 4 and pts[p] - pts[1 - p] >= 2:
winner = args[0]
out.append(None)
elif cmd == "score":
a, b = pts
if winner is not None:
out.append("Game " + winner)
elif a >= 3 and b >= 3:
if a == b:
out.append("Deuce")
elif a > b:
out.append("Advantage Player A")
else:
out.append("Advantage Player B")
else:
out.append(calls[a] + "-" + calls[b])
else:
raise ValueError("Unknown operation")
return out