Codington
0 of 6 problems solved • 0%

Exercise prompt

Diagnose a Ratio

Example

A label must have exactly two fields. Unpacking refuses an unexpected number of fields.

try: name, unit = "weight:kg:extra".split(":") except ValueError: print("Unexpected fields") # printed for this label

Parsing and arithmetic are separate stages. Even a well-formed pair of numbers might fail at the arithmetic stage.

Your task

Implement ratio(text). A ratio has two integer strings separated by one slash. Divide the first value by the second and return the result. Return "invalid" if parsing the fields fails and "undefined" for a valid pair whose divisor is zero. Spaces around numbers are allowed.

ratio(" 9 / 2 ") # 4.5 ratio("9 / ?") # "invalid"