5.1 A test of the most common words

Read the tutorial. Build it yourself is the other way to read this part.

just setup

Since the last part, the walk leaves out ruff, the corpus, the types and the docstring. None of them changes a test. This part begins with their code.

The code before this part. The code after it.

5.1 A function for the most common words

count gives the counts in no useful order. To find the most common words, tally must sort the counts, most common first, and keep the first few. A function, top, does it. It sorts by count, highest first, and then by the word, so that two words with the same count keep one order. Then it keeps the first n.

A patch to src/tally/__init__.py.

A test says what top must give. It gives top three words with their counts, and asks for the two most common.

A patch to tests/test_top.py.

In src/tally/__init__.py, top stands between count and main. It sorts with the key (-pair[1], pair[0]). The key is the count with a minus sign, so that the highest count comes first, and then the word. The new file tests/test_top.py has one test, test_most_common_first.

uv run python -m unittest discover -s tests -q

The four tests pass.

The test of top has the same form as the three tests of count. The walk stops here, before the option --top and the report.

What changed

  • src/tally/__init__.py: sort by count, most common first, then by the word. 5 lines added. The file.
    • look at return sorted(counts.items(), key=lambda pair: (-pair[1], pair[0]))[:n]
  • tests/test_top.py: its test, with three words. New, 8 lines. The file.
The diff of src/tally/__init__.py
@@ -11,6 +11,11 @@ def count(text: str) -> dict[str, int]:
     return counts
 
 
+def top(counts: dict[str, int], n: int) -> list[tuple[str, int]]:
+    "The n most common words, most common first."
+    return sorted(counts.items(), key=lambda pair: (-pair[1], pair[0]))[:n]
+
+
 def main() -> None:
     text = open(sys.argv[1]).read() if len(sys.argv) > 1 else sys.stdin.read()
     for word, n in sorted(count(text).items()):
The diff of tests/test_top.py
@@ -0,0 +1,8 @@
+import unittest
+
+from tally import top
+
+
+class Top(unittest.TestCase):
+    def test_most_common_first(self):
+        self.assertEqual(top({"a": 1, "b": 3, "c": 2}, 2), [("b", 3), ("c", 2)])

This change on GitHub. The code after it.