Skip to content

Instantly share code, notes, and snippets.

@uolter
Created November 26, 2013 15:01
Show Gist options
  • Save uolter/7659822 to your computer and use it in GitHub Desktop.
Save uolter/7659822 to your computer and use it in GitHub Desktop.
Counting characters in a string putting them in a dictionary
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