Skip to content

Instantly share code, notes, and snippets.

@izanbf1803
Last active September 12, 2017 21:27
Show Gist options
  • Save izanbf1803/b0431c169fccd0147943914ba73a640c to your computer and use it in GitHub Desktop.
Save izanbf1803/b0431c169fccd0147943914ba73a640c to your computer and use it in GitHub Desktop.
Convert repeating decimals to fractions.
import sys
def err(section):
print("ERROR [{section}]: Bad input (not a number)".format(section=section))
sys.exit(1)
def stoi(s):
return int("".join(("0" + s)))
def int_repeat(n, k):
x = 1
for _ in range(k - 1):
x = x * 10 + 1
return n * x
def gcd(x, y):
a = max(x, y)
b = min(x, y)
while b > 0:
temp = a % b
a = b
b = temp
return a
while True:
inp = input().lower()
if inp[0:4] == "exit":
sys.exit(0)
inp.replace(",", ".")
# Substract 1, 2 because chars '(' and '.' will be removed from string
dot = inp.find(".") - 1 # dot index
a = inp.find("(") - 2 # repetitive decimals init index -> '('
inp = inp.replace("(", "").replace(")", "").replace(".", "")
num = 0
den = 0
if inp.isdigit():
if dot >= 0:
if a >= 0:
ntimes = 1
diff = abs(a - dot)
if diff > 1: # Convert non repetitive decimal to integer side
a = dot + diff
ntimes = pow(10, diff)
intpart_s = inp[:a+1] # integer part (str)
decpart_s = inp[a+1:] # repetitive decimal part (str)
intpart = stoi(intpart_s) # integer part (int)
decpart = stoi(decpart_s) # repetitive decimal part (int)
exp = pow(10, len(decpart_s)) # 10^(non repetitive decimal places)
num = intpart * exp + decpart - intpart
den = int_repeat(9, len(decpart_s)) * ntimes
else:
intpart_s = inp[:dot+1] # integer part (str)
decpart_s = inp[dot+1:] # decimal part (str)
intpart = stoi(intpart_s) # integer part (int)
decpart = stoi(decpart_s) # decimal part (int)
exp = pow(10, len(intpart_s)) # 10^(integer places)
num = intpart * exp + decpart
den = exp
elif dot < 0:
num = int(inp)
den = 1
else:
err(1)
gcd_num_den = gcd(num, den)
if gcd_num_den == 1:
print("{num}/{den} = {res}\n".format(num=num, den=den, res=num/den))
else:
num_s = num // gcd_num_den # numerator simplified
den_s = den // gcd_num_den # denominator simplified
print("{num_s}/{den_s} = {num}/{den} = {res}\n".format(num=num, den=den, res=num/den,
num_s=num_s, den_s=den_s))
@izanbf1803
Copy link
Author

Usage: use (, ) to denote the repeating part.
Samples:
10.22(3) = 10.223333333333...
35.29(45) = 35.294545454545...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment