DAY 09 OF 100 · Text parsing · exact unit conversion

Medium

Measurements From Three Suppliers.

Today’s challenge

Build the solution

Write a function called normalize_lengths(labels) that converts supplier labels to whole millimeters.

Return contract: A dictionary with millimeters (integer values) and rejected (indexes).

Input bounds: 0–100 labels, each at most 60 characters; number has at most nine digits before the decimal point.

Keep the supplied driver below your implementation. It reads one JSON object and prints your return value as JSON. The driver may also probe the behaviour described above; those probe fields are part of the test input.

  1. A valid label is an unsigned decimal followed by mm, cm, or m, case-insensitively. Allow surrounding whitespace and whitespace between the number and unit.
  2. The number has one or more ASCII digits, optionally followed by a dot and one to three fractional digits. Reject signs, exponent notation, a leading dot, and a trailing dot.
  3. Convert exactly to millimeters. Reject a label if its value would contain a fraction of a millimeter. Keep valid values in their original order and report rejected zero-based indexes.

The Twist: The label 1.25 cm becomes a fractional millimeter and must be rejected, while 0.001 m is exactly one millimeter. Floating-point approximations are unnecessary.

Sample

Input

{"labels":["12 mm","1.2cm","0.001 M","1.25 cm",".5m"]}

Expected output

{"millimeters":[12,12,1],"rejected":[3,4]}
day-9.py
Python 3
Tab inserts four spaces. Press Escape, then Tab to move to the next control, or Shift+Tab to move to the previous control.

Log in or create an account to run code, submit solutions, and save your progress.

Output

Run your code to see the result here.