-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathsolution.py
More file actions
39 lines (33 loc) · 1.01 KB
/
solution.py
File metadata and controls
39 lines (33 loc) · 1.01 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
SUBMIT = True
def char_frequency(s: str) -> dict[str, int]:
"""Counts the frequency of each character in a string."""
counts = {}
for char in s:
if char in counts:
counts[char] += 1
else:
counts[char] = 1
return counts
def test() -> None:
"""Simple self-test for Character Frequency."""
cases = [
("hello", {"h": 1, "e": 1, "l": 2, "o": 1}),
("", {}),
("aA", {"a": 1, "A": 1}),
("mississippi", {"m": 1, "i": 4, "s": 4, "p": 2}),
("123123123", {"1": 3, "2": 3, "3": 3}),
(" ", {" ": 3}),
("!@#!@#", {"!": 2, "@": 2, "#": 2}),
]
for text, expected in cases:
try:
res = char_frequency(text)
assert res == expected, (
f"Failed for text='{text}': expected {expected}, got {res}"
)
except AssertionError as e:
print(f"❌ {e}")
return
print("✅ All tests passed!")
if __name__ == "__main__":
test()