Skip to content

Commit 5345728

Browse files
committed
Add example of using a type statement
1 parent 090172d commit 5345728

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

source-code/typing/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ Type checking can be done using [mypy](http://mypy-lang.org/index.html).
2424
1. `dict_incorrect.py`: code that counts the words in a text read from standard
2525
input. The counts are subsequently normalized to `float`, which is a type
2626
error.
27+
1. `dict_correct_type_statement.py`: same code as `dict_correct.py`, but
28+
with a type variable as type statement.
2729
1. `people_incorrect.py`: code that defines a `People` class, stores some in a
2830
list with mistakes.
2931
1. `duck_typing.py`: example code illustrating duck typing.
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#!/usr/bin/env python
2+
3+
import re
4+
import sys
5+
6+
7+
type Count = dict[str, int]
8+
9+
10+
def word_count(text: str) -> Count:
11+
counts: Count = {}
12+
words = re.split(r"\W+", text)
13+
for word in words:
14+
word = word.lower()
15+
if word not in counts:
16+
counts[word] = 0
17+
counts[word] += 1
18+
return counts
19+
20+
21+
if __name__ == "__main__":
22+
text = " ".join(sys.stdin.readlines())
23+
counts = word_count(text)
24+
for word, count in counts.items():
25+
if word:
26+
print(f"{word}: {count}")

0 commit comments

Comments
 (0)