+1 vote
in Programming Languages by (56.7k points)
I want to calculate the ratio of k numbers in Python. Is there any function for it?

E.g.

If

a, b, c = 15, 18, 30

The answer should be: 5:6:10

1 Answer

+2 votes
by (349k points)
selected by
 
Best answer

I don't think there is any Python function to compute the ratio of numbers directly. 

You need to find the greatest common divisor (GCD) of the given numbers and then divide each of them with GCD to get their ratio.

Here is an example:

>>> import math

>>> a, b, c = 15, 18, 30

>>> h=math.gcd(a,b,c)

>>> h

3

>>> ratio = str(a/h) + ":" + str(b/h) + ":" + str(c/h)

>>> ratio

'5.0:6.0:10.0'

>>> 


...