How to code in Python to get the ratio (x:y) format of given two numbers or for the percentage of the given two numbers

Viewed 2275

Given the number of students and pencils, say students 154 and pencils are 93 how to code in Python to get a ratio.

Output: x:y

Or say given a percentage of two numbers and find the ratio.

Output: x:y

2 Answers
import math 
x = 50
y = 10
print(str(int(round(x / (math.gcd(50, 10)),0))) + ':'+ str(int(round(y / (math.gcd(50, 10)),0))))

Output : 5:1

You want to find the greatest common divisor between you numbers x and y. The math library has the function gcd() for this.

>>> import math
>>> x = 50
>>> y = 10
>>> div = math.gcd(x, y)

You can now print the ratio by dividing your original numbers by div:

>>> print(f"{x/div}:{y/div)")
5:1

In your particular example you will find that the greatest common divider 154 and 93 is 1.

Side note: If you don't want to reedit your code over and over again, use the input() function.

How to find the greatest common divisor?

(If you want to flex a little)

The wikipedia article for greatest common divisor references the Binary GCD Article as a method for calculating the GCD of two numbers.

The algorithm reduces the problem of finding the GCD of two nonnegative numbers v and u by repeatedly applying these identities:

gcd(0, v) = v, because everything divides zero, and v is the largest number that divides v. Similarly, gcd(u, 0) = u.

gcd(2u, 2v) = 2·gcd(u, v)

gcd(2u, v) = gcd(u, v), if v is odd (2 is not a common divisor). Similarly, gcd(u, 2v) = gcd(u, v) if u is odd.

gcd(u, v) = gcd(|u − v|, min(u, v)), if u and v are both odd.

def gcd(a, b):
    if a == b:
        return a

    if a == 0:
        return b
    elif b == 0:
        return a

    #if a is even
    if a % 2 == 0:

        #if b is odd
        if b % 2 == 1:
            return gcd(a/2, b)
        # Both are even
        else:
            return 2 * gcd(a/2, b/2)

    else:
        # a is odd
        if b % 2 == 0:
            # b is even
            return gcd(a, b/2)

        # if a and b are odd a-b must be even
        if (a > b):
            return gcd((a-b)/2, b)
        else:
            return gcd((b-a)/2, a)
Related