CodeEval Trick or Treat

You get as input a string containing in a strictly defined format the number of vampires, zombies, witches, and number of houses they visited.
Each vampire gets 3 candies from each visited house, zombies 4, and witches 5. Return the average number of candy each kid gets, as a truncated integer.
This Halloween-style problem is #220 from CodeEval. I have solved it using Python 3 as implementation language.

The couple of samples provided, that I have converted in python test cases, explain which is the expected input format. As usual, we are not required to perform any error handling whatsoever.
def test_provided_1(self):
    self.assertEqual(4, solution('Vampires: 1, Zombies: 1, Witches: 1, Houses: 1'))

def test_provided_2(self):
    self.assertEqual(36, solution('Vampires: 3, Zombies: 2, Witches: 1, Houses: 10'))
Curiosly, the most interesting part of this problem is in extracting the values from the input string. I decided to work on it firstly splitting it on commas, then splitting each resulting element on ': ' - colon and a blank - so that on the right part of the split is going to be the string representation of the number. The is just a matter of convert it to integer. I wrote all this stuff as a list comprehension, and then I extracted its values on variables with more readable names:
vampires, zombies, witches, houses = [int(item.split(': ')[1]) for item in line.split(',')]
After calculating the numbers of candies, we have return the average of them for kid, as an integer number,
return candies // (vampires + zombies + witches)
Notice that I used the Python 3 integer division operator that returns the floor result of a division, as for requirements.

As by routine, I have pushed test case and Python script to GitHub.

No comments:

Post a Comment