Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Repeating Decimals by Rcp8jzd
import math
def convert(numerator, denominator):
# Adapted from
# https://en.wikipedia.org/wiki/Repeating_decimal#Algorithm_for_positive_bases
pos = -1
occurs = {}
int_part, numerator = divmod(numerator, denominator)
s = str(int_part) + '.'
while numerator not in occurs.keys():
occurs[numerator] = pos
z = math.floor(10 * numerator / denominator)
numerator = numerator * 10 - z * denominator
if numerator == 0:
L = 0
if z != 0:
s += str(z)
return s
s += str(z)
pos -= 1
L = occurs[numerator] - pos
# Mark the digits of the repetend with parentheses
if L > 0:
s = s[:-L] + '(' + s[-L:] + ')'
pass
return s
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert convert(1, 3) == "0.(3)", "1/3 Classic"
assert convert(5, 3) == "1.(6)", "5/3 The same, but bigger"
assert convert(3, 8) == "0.375", "3/8 without repeating part"
assert convert(7, 11) == "0.(63)", "7/11 prime/prime"
assert convert(29, 12) == "2.41(6)", "29/12 not and repeating part"
assert convert(11, 7) == "1.(571428)", "11/7 six digits"
assert convert(0, 117) == "0.", "Zero"
March 21, 2020
Comments: