-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcharacter_count.py
More file actions
41 lines (30 loc) · 1.15 KB
/
character_count.py
File metadata and controls
41 lines (30 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
'''
Problem: Given a S string, count the number that each character appears.
Doctest Exemple:
>>> s = 'hue HUE br'
>>> character_repetition_count(s)
{'h': 2, 'u': 2, 'e': 2, 'b': 1, 'r': 1}
>>> s = 'hue HUE br'
>>> character_repetition_count(s, case_sensitive=True)
{'h': 1, 'u': 1, 'e': 1, 'H': 1, 'U': 1, 'E': 1, 'b': 1, 'r': 1}
>>> s = 'hue HUE br'
>>> character_repetition_count(s, case_sensitive=True, ignore_spaces=False)
{'h': 1, 'u': 1, 'e': 1, ' ': 2, 'H': 1, 'U': 1, 'E': 1, 'b': 1, 'r': 1}
'''
def character_repetition_count(string: str, case_sensitive: bool = False, ignore_spaces: bool = True) -> dict:
'''
Counts the number of character occurences for a given string.
'''
counted = {}
if ignore_spaces:
string = string.replace(' ', '')
if not case_sensitive:
string = string.lower()
for char in string:
counted[char] = counted.get(char, 0) + 1
return counted
if __name__ == "__main__":
s = 'S F X'
print(character_repetition_count(s))
print(character_repetition_count(s, case_sensitive=True))
print(character_repetition_count(s, case_sensitive=True, ignore_spaces=False))