Skip to content

Instantly share code, notes, and snippets.

@derUli
Created March 15, 2025 13:27
Show Gist options
  • Save derUli/91460ac02da8951feeda6f3513b9f066 to your computer and use it in GitHub Desktop.
Save derUli/91460ac02da8951feeda6f3513b9f066 to your computer and use it in GitHub Desktop.
Calculate the aspect ratio of a screen resolution in python
def calculate_aspect(width: int, height: int) -> tuple[int, int]:
""" Calculate aspect ratio of a screen resolution """
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 x, y
print(calculate_aspect(1920, 1080)) # (16, 9)
print(calculate_aspect(1024, 768)) # (4, 3)
print(calculate_aspect(300, 300)) # (1, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment