Advertisement
Guest User

Untitled

a guest
Feb 29th, 2020
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. def count_char(input):
  2. '''
  3. Counts the number of occurrences of each character in a string. The result should be a dictionary where the key is the character and the dictionary is its count.
  4.  
  5. For example,
  6. >>> count_char("HelloOo!")
  7. {'H': 1, 'e': 1, 'l': 2, 'o': 2, 'O': 1, '!': 1}
  8. '''
  9. d = {}
  10. # d = {'H': 1
  11. for c in input:
  12. if c in d: # Is a key named 'H' inside the d?
  13. d[c] = d[c] + 1 #then count 'H'
  14. else:
  15. d[c] = 1 #if there's no 'H' then make the value as 1
  16.  
  17. return d
  18. #pass
  19. """
  20. def test_count_char():
  21. assert count_char("HelloOo!") == {'H': 1, 'e': 1, 'l': 2, 'o': 2, 'O': 1, '!': 1}
  22. def test_empty():
  23. assert count_char("") == {}
  24.  
  25. def test_simple():
  26. assert count_char("abc") == {"a": 1, "b": 1, "c": 1}
  27.  
  28. def test_double():
  29. assert count_char("aa") == {"a": 2}
  30.  
  31. def test_uppercase():
  32. assert count_char("aA") == {"a": 1, "A": 1}
  33. def test_space():
  34. assert count_char("Hi a") == {"H": 1, "i": 1, " ": 1, "a": 1}
  35. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement