diff options
| author | Paulo Custodio <pauloscustodio@gmail.com> | 2021-11-09 16:06:23 +0000 |
|---|---|---|
| committer | Paulo Custodio <pauloscustodio@gmail.com> | 2021-11-09 16:06:23 +0000 |
| commit | 6f1f7bb5384bb1eee4d9cc27380b39c5b13a87f1 (patch) | |
| tree | f3d4fd04604344c3976e7822cd42055e7dcf073d | |
| parent | 30d3fb62781e045bca559f4c4b7b30a646b2e20f (diff) | |
| download | perlweeklychallenge-club-6f1f7bb5384bb1eee4d9cc27380b39c5b13a87f1.tar.gz perlweeklychallenge-club-6f1f7bb5384bb1eee4d9cc27380b39c5b13a87f1.tar.bz2 perlweeklychallenge-club-6f1f7bb5384bb1eee4d9cc27380b39c5b13a87f1.zip | |
Add Python solution to challenge 106 task 2
| -rw-r--r-- | challenge-106/paulo-custodio/perl/ch-2.pl | 2 | ||||
| -rw-r--r-- | challenge-106/paulo-custodio/python/ch-2.py | 39 |
2 files changed, 40 insertions, 1 deletions
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]))) |
