Pythagorean Triplet2026-04-28
My Solution: Exercism Pythagorean Triplet solution
Instructions
A Pythagorean triplet is a set of three natural numbers, {a, b, c}, for which:
a^2 + b^2 = c^2
and such that:
a < b < c
Given an input integer N, find all Pythagorean triplets for which a + b + c = N.
For example, with N = 1000, there is exactly one Pythagorean triplet for which a + b + c = 1000: {200, 375, 425}.
Return a list of lists, such as [[a, b, c]]. The order of the outer list does not matter.
Solution
def triplets_with_sum(number):
# We can solve this by combining the two equations:
# c = number - a - b
# a^2 + b^2 = c^2
# which gives:
# b = (number^2 - 2 * number * a) / (2 * (number - a))
triplets = []
for a in range(1, number // 3):
numerator = (number ** 2) - (2 * number * a)
denominator = 2 * (number - a)
if numerator % denominator == 0:
b = numerator // denominator
c = number - a - b
if a < b < c:
triplets.append([a, b, c])
return triplets
Syntax Notes
- The sum condition lets us write
cin terms ofa,b, andnumber. - Substituting that into
a^2 + b^2 = c^2gives a direct formula forb. range(1, number // 3)is enough becauseamust be the smallest value in the triplet.- The
numerator % denominator == 0check ensuresbis a whole number. - The
a < b < ccheck filters out duplicates and keeps the triplet in ascending order.