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')) # 31. '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