Pages

CodeEval Black card

Given in input a string containing a list of blank separated names, a pipe, and "black spot" number, eliminate one after the other all the names but one, as in a couting rhyme. Return the name of the surviver. This is the CodeEval problem #222.

Before starting developing my Python 3 code, I converted the given samples in test cases.
def test_provided_1(self):
    self.assertEqual('Sara', solution('John Sara Tom Susan | 3'))

def test_provided_2(self):
    self.assertEqual('Mary', solution('John Tom Mary | 5'))
It's easy to get what the code should do, executing by hand a sample. For the first one, Tom is the third element, so he's out. Susan becomes third, she's out. John is the first, aka third modulo two, he's out too. Sara is the only surviver, she is the winner.

This is my solution:
def solution(line):
    data = line.split(' | ')
    players = data[0].split() # 1
    black = int(data[1]) - 1 # 2

    while len(players) > 1: # 3
        del players[black if black < len(players) else black % len(players)]
    return players[0]
1. Convert the first part of the input string to a list, splitting on blanks, resulting in a list of names.
2. We should start counting from the first name, considering it as 'one' in the counting rhyme. To adjust this to the fact that in Python we start counting from zero, I decrease here the black spot number.
3. While there is more than one player, remove an element from the list. I did it by the del operator, using the plain black number when possible, otherwise its modulo on the current list length.

I have pushed to GitHub the full Python script and its associated test case.

No comments:

Post a Comment