Problem 581201 · easy · Level 05 Advanced Algorithms & Graphs

Say What the Helpers Take

py-type-hints · type aliases · Callable · optional values

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): points is a list of Points. Return the point whose coordinates are the means of the coordinates, as a Point, or None for an empty list.
  • nearest(query, points, dist): query is a Point, points a list of Points, and dist a function that takes two Points and returns a float. Return the index of the point closest to query according to dist (the smallest index among ties), or None for an empty list.
  • word_counts(text): text is 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): values is a list of floats and factor a float. Return a new list of floats with every value multiplied by factor.

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**4 points 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`
Starting Python…