Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active May 7, 2024 05:59
Show Gist options
  • Select an option

  • Save Integralist/4ca9ff94ea82b0e407f540540f1d8c6c to your computer and use it in GitHub Desktop.

Select an option

Save Integralist/4ca9ff94ea82b0e407f540540f1d8c6c to your computer and use it in GitHub Desktop.
[Calculate Aspect Ratio] #aspect #ratio #python
def calculate_aspect(width: int, height: int) -> str:
def gcd(a, b):
"""The GCD (greatest common divisor) is the highest number that evenly divides both width and height."""
return a if b == 0 else gcd(b, a % b)
r = gcd(width, height)
x = int(width / r)
y = int(height / r)
return f"{x}:{y}"
calculate_aspect(1920, 1080) # '16:9'
@Integralist

Integralist commented Aug 2, 2017

Copy link
Copy Markdown
Author

Slight alternative...

def calculate_aspect(width: int, height: int) -> str:
    temp = 0

    def gcd(a, b):
        """The GCD (greatest common divisor) is the highest number that evenly divides both width and height."""
        return a if b == 0 else gcd(b, a % b)

    if width == height:
        return "1:1"

    if width < height:
        temp = width
        width = height
        height = temp

    divisor = gcd(width, height)

    x = int(width / divisor) if not temp else int(height / divisor)
    y = int(height / divisor) if not temp else int(width / divisor)

    return f"{x}:{y}"

@qodzero

qodzero commented Jan 11, 2019

Copy link
Copy Markdown

Thanks, this just saved my day

@gusbemacbe

Copy link
Copy Markdown

@Integralist, both Python files did not return the result, and the result was empty.

@rpong

rpong commented Apr 3, 2020

Copy link
Copy Markdown

👍🏼thanks!

@trey

trey commented May 23, 2020

Copy link
Copy Markdown

Thank you!

@panchoRod

Copy link
Copy Markdown

thanks

@alpden550

alpden550 commented Sep 2, 2021

Copy link
Copy Markdown
import math


def calculate_aspect(width: int, height: int) -> str:
    r = math.gcd(width, height)
    x = int(width / r)
    y = int(height / r)
    return f"{x}:{y}"

@AbelSalazarDev

Copy link
Copy Markdown
import math


def calculate_aspect(width: int, height: int) -> str:
    r = math.gcd(width, height)
    x = int(width / r)
    y = int(height / r)
    return f"{x}:{y}"

Gracias!

@neksid25

Copy link
Copy Markdown
def func(x: int, y: int) -> tuple:
    for i in range(1, (y if x > y else x)+1):
        if x % i == 0 and y % i == 0: hcf = i
    return (x // hcf, y // hcf)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment