Skip to content

Instantly share code, notes, and snippets.

@mportesdev
Last active June 29, 2020 12:51
Show Gist options
  • Save mportesdev/06399b4d07789bac8c30a9ca0302e148 to your computer and use it in GitHub Desktop.
Save mportesdev/06399b4d07789bac8c30a9ca0302e148 to your computer and use it in GitHub Desktop.
Pythagorean triples

Find Pythagorean triples (x, y, z) such that x**2 + y**2 == z**2 and x + y + z == n.

import math
from itertools import combinations


def triples(n):
    for x, y in combinations(range(1, n), 2):
        z = n - x - y
        if z > y and math.hypot(x, y) == z:
            yield x, y, z
>>> list(triples(120))
[(20, 48, 52), (24, 45, 51), (30, 40, 50)]

>>> list(triples(3000))
[(500, 1200, 1300), (600, 1125, 1275), (750, 1000, 1250)]

>>> list(triples(12144))
[(1012, 5520, 5612), (2622, 4400, 5122), (3036, 4048, 5060), (3312, 3795, 5037), (3432, 3680, 5032)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment