forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecimal_to_fraction.py
62 lines (60 loc) · 1.92 KB
/
decimal_to_fraction.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
defdecimal_to_fraction(decimal: float|str) ->tuple[int, int]:
"""
Return a decimal number in its simplest fraction form
>>> decimal_to_fraction(2)
(2, 1)
>>> decimal_to_fraction(89.)
(89, 1)
>>> decimal_to_fraction("67")
(67, 1)
>>> decimal_to_fraction("45.0")
(45, 1)
>>> decimal_to_fraction(1.5)
(3, 2)
>>> decimal_to_fraction("6.25")
(25, 4)
>>> decimal_to_fraction("78td")
Traceback (most recent call last):
ValueError: Please enter a valid number
>>> decimal_to_fraction(0)
(0, 1)
>>> decimal_to_fraction(-2.5)
(-5, 2)
>>> decimal_to_fraction(0.125)
(1, 8)
>>> decimal_to_fraction(1000000.25)
(4000001, 4)
>>> decimal_to_fraction(1.3333)
(13333, 10000)
>>> decimal_to_fraction("1.23e2")
(123, 1)
>>> decimal_to_fraction("0.500")
(1, 2)
"""
try:
decimal=float(decimal)
exceptValueError:
raiseValueError("Please enter a valid number")
fractional_part=decimal-int(decimal)
iffractional_part==0:
returnint(decimal), 1
else:
number_of_frac_digits=len(str(decimal).split(".")[1])
numerator=int(decimal* (10**number_of_frac_digits))
denominator=10**number_of_frac_digits
divisor, dividend=denominator, numerator
whileTrue:
remainder=dividend%divisor
ifremainder==0:
break
dividend, divisor=divisor, remainder
numerator, denominator=numerator//divisor, denominator//divisor
returnnumerator, denominator
if__name__=="__main__":
print(f"{decimal_to_fraction(2) =}")
print(f"{decimal_to_fraction(89.0) =}")
print(f"{decimal_to_fraction('67') =}")
print(f"{decimal_to_fraction('45.0') =}")
print(f"{decimal_to_fraction(1.5) =}")
print(f"{decimal_to_fraction('6.25') =}")
print(f"{decimal_to_fraction('78td') =}")