from fractions import Fraction
"""
convert_decimal_to_rational(s)
-------------------------------
Converts a decimal number (given as a string) into an exact rational p/q.
Why Python makes this easy:
• Python's built‑in Fraction class can convert decimals exactly.
• It handles reduction automatically.
• It avoids floating‑point inaccuracies by accepting strings directly.
Algorithm (handled internally by Fraction):
1. Parse the string.
2. Convert integer and fractional parts into numerator/denominator.
3. Reduce using gcd.
"""
def convert_decimal_to_rational(s: str) -> Fraction:
# Fraction(s) interprets the string exactly, avoiding float rounding issues.
return Fraction(s)
def main():
values = [
"3.5", "12.75", "0.125", "100.001",
"7", "42.0", "0.333", "5.2"
]
for v in values:
r = convert_decimal_to_rational(v)
print(f"{v} -> {r.numerator}/{r.denominator}")
if __name__ == "__main__":
main()
"""
run:
3.5 -> 7/2
12.75 -> 51/4
0.125 -> 1/8
100.001 -> 100001/1000
7 -> 7/1
42.0 -> 42/1
0.333 -> 333/1000
5.2 -> 26/5
"""