Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find least common denominator for list of fractions in python

I have a list of fractions

from fractions import Fraction

fractions_list=[Fraction(3,14),Fraction(1,7),Fraction(9,14)]

The output should be a list with the numerators for each fraction, then the denominator for all of them at the end and in simplest form. For above example the result (3/14, 2/14, 9/14) would be represented as follows

[3,2,9,14]

Is there an elegant solution for this? All I can think of involves a lot of intermediate lists to store some variables and scales horribly.

like image 723
Max Avatar asked Apr 06 '20 06:04

Max


1 Answers

import numpy as np

fractions_list=[Fraction(3,14),Fraction(1,7),Fraction(9,14)]

lcm = np.lcm.reduce([fr.denominator for fr in fractions_list])

vals = [int(fr.numerator * lcm / fr.denominator) for fr in fractions_list]
vals.append(lcm)
like image 105
Tom Ron Avatar answered Nov 14 '22 07:11

Tom Ron