Created
June 22, 2012 15:14
-
-
Save doctorlove/2973378 to your computer and use it in GitHub Desktop.
self_counting.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import unittest | |
# 100000000 means 1 one and 0 of anything else, up to 9. | |
def is_self_counting(number, max): | |
lookup = [1,2,3,4,5,6,7,8,9,0] | |
print "Checking", number | |
for i in range(0,max): | |
count = number.count(lookup[i]) | |
if count <> number[i]: | |
return False | |
return True | |
def find_self_counting(max): | |
print "from", 10**(max-1), "to", 10**max - 1, "using max", max | |
#for i in xrange(10**(max-1),10**max): | |
for i in xrange(0,1000000000): | |
l = to_string(i, max) | |
#print i, l | |
if sum(l) <= max: | |
if is_self_counting(l, max): | |
print "self counting", i | |
def to_string(i, max): | |
pos = 0 | |
l = [0 for t in range (0,max)] | |
for c in str(i): | |
l[pos] = int(c) | |
pos = pos + 1 | |
return l | |
class SelfCountingTests(unittest.TestCase): | |
def test_that_known_ten_digit_number_is_self_counting_for_max_10(self): | |
i = 2100010006 | |
max = 10 | |
l = to_string(i, max) | |
self.assertTrue(is_self_counting(l, max)) | |
def test_that_known_one_digit_number_is_self_counting_for_max_1(self): | |
i = 1 | |
max = 1 | |
l = to_string(i, max) | |
self.assertTrue(is_self_counting(l, max)) | |
def test_that_2_is_not_self_counting_for_max_1(self): | |
i = 2 | |
max = 1 | |
l = to_string(i, max) | |
self.assertFalse(is_self_counting(l, max)) | |
def test_that_known_nine_digit_number_is_self_counting_for_max_9(self): | |
i = 100000000 | |
max = 9 | |
l = to_string(i, max) | |
self.assertTrue(is_self_counting(l, max)) | |
def test_that_123456789_is_not_self_counting_for_max_9(self): | |
i = 123456789 | |
max = 9 | |
l = to_string(i, max) | |
self.assertFalse(is_self_counting(l, max)) | |
if __name__ == "__main__": | |
if len(sys.argv) > 1 and sys.argv[1] == "--test": | |
unittest.main(argv = sys.argv[1:]) | |
else: | |
find_self_counting(9) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment