python function to simplify fraction

时间:2017-04-20 15:31:03

标签: python-3.x fractions

I am trying to write a function that will help me break down a fraction into simple components like so

enter image description here

我写了这个函数

from fractions import Fraction
def lowest_fraction(frac):
    num = frac[0]
    den = frac[-1]
    if frac == (1, den):
        yield frac
    while frac != (1, den):
        new_num = num - num//2
        rem = num - new_num
        new_frac = Fraction(new_num, den)
        frac = (new_frac.numerator, new_frac.denominator)
        num = rem
        yield frac

我跑了下面的

for each in [(1, 2), (3, 4), (3, 8), (5, 8), (7, 8), (7, 16), (9, 32)]:
    print('{}: '.format(each))
    for k in lowest_fraction(each):
        print('\t{}'.format(k))

这是输出

(1, 2): 
    (1, 2)
(3, 4): 
    (1, 2)
    (1, 4)
(3, 8): 
    (1, 4)
    (1, 8)
(5, 8): 
    (3, 8)
    (1, 8)
(7, 8): 
    (1, 2)
    (1, 4)
    (1, 8)
(7, 16): 
    (1, 4)
    (1, 8)
    (1, 16)
(9, 32): 
    (5, 32)
    (1, 16)
    (1, 32)

您可以看到(3, 8)(9, 32)的输出不是最简单的形式。我想我想做的事情可以通过编写递归代码来完成,但我现在不能写一个,因为我还没有完全掌握递归的概念。

0 个答案:

没有答案