简体   繁体   English

如何使纯 python 中的分数列表具有相同的分母

[英]How to make list of fractions in pure python have the same denominator

It's a simple problem really, but I have been searching all over and cannot find the answer.这确实是一个简单的问题,但我一直在寻找并找不到答案。 Let's assume that we have a list of fractions made using the fractions module in python:假设我们有一个使用 python 中的fractions模块生成的分数列表:

from fractions import Fraction

A = [Fraction(1, 3), Fraction(4, 14), Fraction(8, 21)]

I want to put them all on one base denominator.我想把它们都放在一个基本分母上。 The output would be a list of all of the numerators plus the common denominator: output 将是所有分子加上公分母的列表:

"""
A[0] ==> 7/21
A[1] ==> 6/21
A[2] ==> 8/21

Notice that the denominator 21 is the lowest we can go. 
"""

B = [7, 6, 8, 21] # Desired output style

How would I go about doing this in pure python (only using built in libraries) .我将如何 go 在纯 python 中执行此操作(仅使用内置库)

There might be more elegant solutions than this but this works:可能有比这更优雅的解决方案,但这有效:

  1. You identify the combinations of you denominators您确定分母的组合

    import itertools combinations = itertools.combinations([x.denominator for x in A],2)

This will be an iterator: Then you find the least common multiplier with this function: Credit goes to this answer :这将是一个迭代器:然后你找到这个 function 的最小公倍数:归功于这个答案

import math

def lcm(a, b):
    return abs(a*b) // math.gcd(a, b)

Then you run it on your iterator:然后你在你的迭代器上运行它:

from functools import reduce
x = 1
for item in combinations:
    res = reduce(lcm, (a for a in item))
    if res > x:
        x = res

This gives you 21 I think from here it is easy to divide this with the denominator and multiply your numerator with that这给了你 21 我认为从这里很容易将它与分母相除,然后将你的分子乘以那个

Hint for your desired output - this although does not contain x (21) yet:提示您想要的 output - 虽然它不包含 x (21) :

[(a * x/a.denominator).numerator for a in A]
from fractions import Fraction
import numpy as np

def reduction_fraction(A):    
    deno = []
    # get all the denominators
    for fraction in A:
        deno.append(fraction.denominator)
    
    result = []
    # put all the fraction on the least common multiple of the denominators
    for fraction in A:
        result.append(fraction.numerator * np.lcm.reduce(deno) / fraction.denominator)

    # add the least common multiple of the denominators at the end
    result.append(np.lcm.reduce(deno))

    return result

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

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