A machine-learning notebook has a few small helpers that everybody calls, and nobody remembers what they accept. Write them again with type hints, so the signature says it all. Define a type alias Point for a point in the plane: a tuple of two floats. Then write:
centroid(points):pointsis a list ofPoints. Return the point whose coordinates are the means of the coordinates, as aPoint, orNonefor an empty list.nearest(query, points, dist):queryis aPoint,pointsa list ofPoints, anddista function that takes twoPoints and returns a float. Return the index of the point closest toqueryaccording todist(the smallest index among ties), orNonefor an empty list.word_counts(text):textis a string. Return a dictionary from each lower-cased word (split on whitespace) to the number of times it occurs, as whole numbers.scaled(values, *, factor=1.0):valuesis a list of floats andfactora float. Return a new list of floats with every value multiplied byfactor.
Annotate every parameter and every result. Use the built-in generic forms (list[float], dict[str, int], tuple[float, float]), X | None for a value that may be missing, and Callable from collections.abc (or typing) for the function parameter. The tests read your hints with the setup helper hints_of(fn), which lists them as text (the older spellings List[float] and Optional[int] count as the same), type_text(Point) shows your alias, and raises(fn, *args) returns the name of the exception a call raises (or None).
Examples
Input: hints_of(centroid)
Output: [("points", "list[tuple[float, float]]"), ("return", "tuple[float, float] | None")]
Input: centroid([(0.0, 0.0), (4.0, 0.0), (2.0, 6.0)]), nearest((1.0, 1.0), [(5.0, 5.0), (1.5, 0.5)], math.dist)
Output: ((2.0, 2.0), 1)
Constraints
- Up to
10**4points or words. Hints are not checked when the program runs; the tests read them.
Goals
- Annotate parameters and results with `list[...]`, `dict[...]`, `tuple[...]` and `X | None`
- Name a repeated type with a type alias
- Describe a function passed as an argument with `Callable`