| > I probably would break the function down into smaller parts Sure. Internally I have multiple functions. Though I don't like unit testing below the public API as it inhibits refactoring and gives false coverage feedback, so all my tests go through the main API. > Pasting that into Claude, without any other context The context is the important part. Like the context which says "0.5E0" and "nan" are specifically not supported, and how the calculations need to use decimal arithmetic, not IEEE 754 float64. Also, the hard part is generating the complement with correct formatting, not parsing float-or-fraction, which is first-year CS assignment. > # Handle special values Python and C accept "Infinity" as an alternative to "Inf". The correct way is to defer to the underlying system then check if the returned value is infinite or a NaN. Which is what will happen here because when those string checks fail, and the check for "/" fails, it will correctly process through float(). Yes, this section isn't needed. > # Handle empty string My spec says the empty string is not an error. > numerator, denominator = text.split("/"); num = float(numerator); den = float(denominator) This allows "1.2/3.4" and "inf/nan", which were not in the input examples and therefore support for them should be interpreted as accidental scope creep. They were also not part of the test suite, which means the tests cannot distinguish between these two clearly different implementations: num = float(numerator)
den = float(denominator)
and: num = int(numerator)
den = int(denominator)
Here's a version which follows the same style as the linked-to code, but is easier to understand: if not isinstance(text, str):
return None
# Remove whitespace
text = text.strip()
# Handle empty string
if not text:
return None
# Handle ratio format (e.g., "1/2")
if "/" in text:
try:
numerator, denominator = text.split("/")
num = int(numerator)
den = int(denominator)
if den == 0:
return float("inf") if num > 0 else float("-inf") if num < 0 else float("nan")
return num / den
except ValueError:
return None
# Handle regular numbers (inf, nan, scientific notation, etc.)
try:
return float(text)
except ValueError:
return None
It still doesn't come anywhere near handling the actual problem spec I gave. |