简体   繁体   English

在 python 中找到分数列表的最小公分母

[英]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. output 应该是一个列表,其中包含每个分数的分子,然后是所有分数的分母,并且是最简单的形式。 For above example the result (3/14, 2/14, 9/14) would be represented as follows对于上述示例,结果 (3/14, 2/14, 9/14) 将表示如下

[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.我能想到的所有内容都涉及大量中间列表来存储一些变量和可怕的规模。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM