Pages

CodeEval Self Describing Numbers

Tell if the number passed in is self-describing, returning 1 in case of success. That number, also known as self-descriptive number, is such that it has in each digit, starting from the leftmost, the number of that digit in the number itself. If this definition looks confusing to you, you are not alone. Have a look to the CodeEval page for this problem, or to the tests here below.

Based on the provided samples, I wrote these tests:
def test_provided_1(self):
    self.assertEqual(1, solution('2020'))  # 1

def test_provided_2(self):
    self.assertEqual(0, solution('22'))  # 2

def test_provided_3(self):
    self.assertEqual(1, solution('1210'))  # 3
1. '2020' has two 0's, no 1's, two 2's, zero 3's. So it is self describing.
2. '22' has two 2's. To be self-describing it should have two 0's and two 1's. So it is not.
3. One 0's, two 1's, one 2's, zero 3's. Yes, it is.

Got it? we say it is self-describing if all its digits have the value of the respective digits counted in the number.

We could write very compact Python solutions to this problem, almost one-liners, still easy to undestand.

First part, we need to count the digits in the input string. The Counter class in collections is designed right for this task:
from collections import Counter

counter = Counter(map(int, line))
I take the input line (that I name "line"), I map its elements to int, and I use them to initialize an object of the class Counter.

Then I use the built-in all to check all the digit in the range from zero to the string size (right open interval, as python standard). If they are all the same value of the counter for the respective digit, I return 1:
return int(all(counter[i] == int(line[i]) for i in range(len(line))))
Simple and convincing, isn't it?

The complete python3 script and unit test is on GitHub.

No comments:

Post a Comment