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.
To simplify a ratio, start by factoring out both numbers in the ratio. Then, find the greatest common factor, which is the highest factor that both numbers in the ratio share. Finally, divide both numbers by the greatest common factor to get the simplified ratio.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With