Search code examples
pythonlistfractions

Dividing a list by a list with output as fractions


I want to divide one list of integers by another list of integers, with the output given as fractions (not decimals). From the question "How to combine elements from two lists into a third?", I found a great answer, specifically:

a  =   [3,    6,   8,   65,   3]
b  =   [34,   2,   5,   3,    5]
c = [float(x)/y for x,y in zip(a,b)]
print(c)

The only problem is that this code outputs decimals and I'm looking for fractions. I suspect I need to use term like float, but for fractions instead of decimals? I could also try to convert the output of the above code to fractions, but I suspect that would be more complicated because of the imprecision of repeating decimals.

Further notes: the two lists I want to use all will produce fractions which require reduction. My lists have 49 items each, but to show the code more concisely, I've reduced them to 10 each.

a = [6198089008491993412800, 3099044504245996706400, 2066029669497331137600, 2324283378184497529800, 1239617801698398682560, 2066029669497331137600, 1328161930391141445600, 1549522252122998353200, 1033014834748665568800, 1549522252122998353200]
b = [3099044504245996706400, 2066029669497331137600, 2324283378184497529800, 1239617801698398682560, 2066029669497331137600, 1328161930391141445600, 1549522252122998353200, 1033014834748665568800, 1549522252122998353200, 1126925274271271529600]
c = [float(x)/y for x,y in zip(b,a)]

print(c)

[0.5, 0.6666666666666666, 1.125, 0.5333333333333333, 1.6666666666666667, 0.6428571428571428, 1.1666666666666667, 0.6666666666666666, 1.5, 0.7272727272727272]

The result I am looking for is:

1/2, 2/3, 9/8, 8/15, 5/3, 9/14, 7/6, 2/3, 3/2, 8/11

Solution

  • You can use fractions module:

    import fractions
    
    a = [
        6198089008491993412800,
        3099044504245996706400,
        2066029669497331137600,
        2324283378184497529800,
        1239617801698398682560,
        2066029669497331137600,
        1328161930391141445600,
        1549522252122998353200,
        1033014834748665568800,
        1549522252122998353200,
    ]
    
    b = [
        3099044504245996706400,
        2066029669497331137600,
        2324283378184497529800,
        1239617801698398682560,
        2066029669497331137600,
        1328161930391141445600,
        1549522252122998353200,
        1033014834748665568800,
        1549522252122998353200,
        1126925274271271529600,
    ]
    
    for x, y in zip(b, a):
        print(fractions.Fraction(x, y))
    

    Prints:

    1/2
    2/3
    9/8
    8/15
    5/3
    9/14
    7/6
    2/3
    3/2
    8/11