I want to write a function in Python 3 that converts fractions given as numerator and denominator into their string representation as decimal number, but with repeating decimal places in brackets.
An example:
convert(1, 4)
should output "0.25"
convert(1, 3)
should output "0.(3)"
instead of "0.3333333333"
convert(7, 11)
should output "0.(63)"
instead of "0.6363636364"
convert(29. 12)
should output "2.41(6)"
instead of "2.4166666667"
My current code is at the end of the question, but it fails if there are non-repeating and repeating decimal places. Here's an example run including the debug output (commented print
calls):
----> 29 / 12
5
appended 4
2
appended 1
8
index 2 ['29', 2, 8] result ['2.', '4', '(', '1']
repeating 8
['2.', '4', '(', '1', ')']
What am I doing wrong here?
My code:
def convert(numerator, denominator):
#print("---->", numerator, "/", denominator)
result = [str(numerator//denominator) + "."]
subresults = [str(numerator)]
numerator %= denominator
while numerator != 0:
#print(numerator)
numerator *= 10
result_digit, numerator = divmod(numerator, denominator)
if numerator not in subresults:
subresults.append(numerator)
result.append(str(result_digit))
#print("appended", result_digit)
else:
result.insert(subresults.index(numerator), "(")
#print("index", subresults.index(numerator), subresults, "result", result)
result.append(")")
#print("repeating", numerator)
break
#print(result)
return "".join(result)
Your code just needed some minor changes (see the comments below):
def convert(numerator, denominator):
#print("---->", numerator, "/", denominator)
result = [str(numerator//denominator) + "."]
subresults = [numerator % denominator] ### changed ###
numerator %= denominator
while numerator != 0:
#print(numerator)
numerator *= 10
result_digit, numerator = divmod(numerator, denominator)
result.append(str(result_digit)) ### moved before if-statement
if numerator not in subresults:
subresults.append(numerator)
#print("appended", result_digit)
else:
result.insert(subresults.index(numerator) + 1, "(") ### added '+ 1'
#print("index", subresults.index(numerator), subresults, "result", result)
result.append(")")
#print("repeating", numerator)
break
#print(result)
return "".join(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With