From 6f1f7bb5384bb1eee4d9cc27380b39c5b13a87f1 Mon Sep 17 00:00:00 2001 From: Paulo Custodio Date: Tue, 9 Nov 2021 16:06:23 +0000 Subject: Add Python solution to challenge 106 task 2 --- challenge-106/paulo-custodio/perl/ch-2.pl | 2 +- challenge-106/paulo-custodio/python/ch-2.py | 39 +++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 challenge-106/paulo-custodio/python/ch-2.py diff --git a/challenge-106/paulo-custodio/perl/ch-2.pl b/challenge-106/paulo-custodio/perl/ch-2.pl index 390fa68cb1..aa2f756590 100644 --- a/challenge-106/paulo-custodio/perl/ch-2.pl +++ b/challenge-106/paulo-custodio/perl/ch-2.pl @@ -1,4 +1,4 @@ -#!/usr/bin/perl +#!/usr/bin/env perl # TASK #2 › Decimal String # Submitted by: Mohammad S Anwar diff --git a/challenge-106/paulo-custodio/python/ch-2.py b/challenge-106/paulo-custodio/python/ch-2.py new file mode 100644 index 0000000000..6a019e26d6 --- /dev/null +++ b/challenge-106/paulo-custodio/python/ch-2.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 + +# TASK #2 > Decimal String +# Submitted by: Mohammad S Anwar +# You are given numerator and denominator i.e. $N and $D. +# +# Write a script to convert the fraction into decimal string. If the fractional +# part is recurring then put it in parenthesis. +# +# Example +# Input: $N = 1, $D = 3 +# Output: "0.(3)" +# +# Input: $N = 1, $D = 2 +# Output: "0.5" +# +# Input: $N = 5, $D = 66 +# Output: "0.0(75)" + +import sys +import re +from decimal import * + +def frac2str(n, d): + getcontext().prec = 1000 + getcontext().rounding = ROUND_DOWN + + n = Decimal(n) + d = Decimal(d) + q = str(n/d) + + for rept in range(1,101): + match = re.search(r"((\d{"+str(rept)+r"})\2+\d*)", q) + if match: + q = re.sub(match.group(1), "("+match.group(2)+")", q) + return q + return q + +print(frac2str(int(sys.argv[1]), int(sys.argv[2]))) -- cgit