Seles II: Tennis coding challenge solution

In a previous post, I described a coding challenge sent to me by my colleague. Here is the challenge again:

There is a tennis match between two players denoted 1, and 2. You are given a sequence of 1s and 2s whereby each number denotes a point won by player 1 or player 2 (e.g. 1,2,2,1,2,2 in this example player 2 wins the game to 30). Given the full sequence of the match and the assumption that you are aware of the rules and scoring of tennis, write a programme that determines the winner of the game, given any sequence, inclusive of all boundary cases. NB: The sequence is given in the form of a list called match. In the case above match = (1,2,2,1,2,2)

Points are awarded for a) code that successfully solves the challenge b) time to solve (time yourself) and c) lines of code for efficiency (shorter is better).

My solution was… let’s say… over-engineered.

He did tell me that the winner (the challenge was set in an international coding competition) solved it in a ridiculously short time. He didn’t tell me how short which I think would have led me to take a different approach.

The clue is in the question

Notice that it says:

Given the full sequence of the match[…]

My solution didn’t use this assumption and instead focussed on finding the winner from all possible outcomes. The full sequence of the match means that the last point is the winning point. This means that you just need to check what the last point in the list is to find the winner.

Oh how I cringed!

The winner apparently took 30 seconds to code their solution.

This is Andy’s solution, coded in Python.

def tenniswinner():
    match = (1,2,2,1,2,2)
    w = match[-1]
    if w == 1:
        print("Player 1 is the winner!")
    elif w == 2:
        print("Player 2 is the winner!")

He says: The key insight is that in a match played to tennis rules (and not just a casual knockabout), the winner of the match, is always the player to score the last point. Therefore one needs only return the final element of the list and match it to an if/elif test.

I can see that this solution works and answers the challenge. It would need modifying to handle any list being passed to it, but again, the question doesn’t actually say that the list will vary.

One thought on “Seles II: Tennis coding challenge solution

Comments are closed.