Created
November 26, 2013 15:01
-
-
Save uolter/7659822 to your computer and use it in GitHub Desktop.
Counting characters in a string putting them in a dictionary
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 | |
def count(text): | |
# if the text is None or empty do nothing | |
if text: | |
text = text.replace(' ', '') | |
else: | |
return None | |
# count the element. | |
counter = {} | |
for c in text: | |
if not c in counter: | |
counter[c] = text.count(c) | |
return counter | |
class TestCount(unittest.TestCase): | |
def setUp(self): | |
pass | |
def test_none_str(self): | |
self.assertEqual(count(None), None) | |
def test_empty_str(self): | |
self.assertEqual(count(''), None) | |
def test_empty_blank(self): | |
self.assertEqual(count(' '), {}) | |
def test_count(self): | |
self.assertEqual(count('abbcccdddd'), {'a':1, 'b':2, 'c':3, 'd':4}) | |
if __name__ == '__main__': | |
try: | |
text = sys.argv[1] | |
counter = count(text) | |
if counter: | |
for key in sorted(counter.iterkeys()): | |
print "%s %s" % (key, counter[key]) | |
except IndexError: | |
print 'Missed text.' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment