Search code examples
pythonfractions

How does one simplify a complicated ratio?


Is there a simple way to simplify a ratio down? For example 1875:5625:625 would become 3:9:1.

I am using Python, but I'd like to know why and not just how.


Solution

  • Edit: Please note that fractions.gcd has been Deprecated since Python 3.5: Use math.gcd() instead.

    There's a built-in gcd function in the fractions module so utilizing it I was able to get decent output:

    from fractions import gcd
    
    ratio = '1875:5625:625'
    
    def solve(ratio):
        numbers = [int(i) for i in ratio.split(':')]
        denominater = reduce(gcd,numbers)
        solved = [i/denominater for i in numbers]
        return ':'.join(str(i) for i in solved)
    
    ratio_2_solve =  solve(ratio)
    print ratio_2_solve
    #3:9:1
    

    So given the ratio

    1875:5625:625 
    

    It would produce :

    3:9:1
    

    But that's not the best part of it, you could even put ratios like:

    '1875:5625:625:5000:46875:46250'
    

    And still get the output of:

    3:9:1:8:75:74