|
| 1 | +""" |
| 2 | +If p is the perimeter of a right angle triangle with integral length sides, |
| 3 | +{a,b,c}, there are exactly three solutions for p = 120. |
| 4 | +{20,48,52}, {24,45,51}, {30,40,50} |
| 5 | +
|
| 6 | +For which value of p ≤ 1000, is the number of solutions maximised? |
| 7 | +""" |
| 8 | + |
| 9 | +from typing import Dict |
| 10 | +from collections import Counter |
| 11 | + |
| 12 | + |
| 13 | +def pythagorean_triple(max_perimeter: int) -> Dict: |
| 14 | + """ |
| 15 | + Returns a dictionary with keys as the perimeter of a right angled triangle |
| 16 | + and value as the number of corresponding triplets. |
| 17 | + >>> pythagorean_triple(15) |
| 18 | + Counter({12: 1}) |
| 19 | + >>> pythagorean_triple(40) |
| 20 | + Counter({12: 1, 30: 1, 24: 1, 40: 1, 36: 1}) |
| 21 | + >>> pythagorean_triple(50) |
| 22 | + Counter({12: 1, 30: 1, 24: 1, 40: 1, 36: 1, 48: 1}) |
| 23 | + """ |
| 24 | + triplets = Counter() |
| 25 | + for base in range(1, max_perimeter + 1): |
| 26 | + for perpendicular in range(base, max_perimeter + 1): |
| 27 | + hypotenuse = (base * base + perpendicular * perpendicular) ** 0.5 |
| 28 | + if hypotenuse == int((hypotenuse)): |
| 29 | + perimeter = int(base + perpendicular + hypotenuse) |
| 30 | + if perimeter > max_perimeter: |
| 31 | + continue |
| 32 | + else: |
| 33 | + triplets[perimeter] += 1 |
| 34 | + return triplets |
| 35 | + |
| 36 | + |
| 37 | +if __name__ == "__main__": |
| 38 | + triplets = pythagorean_triple(1000) |
| 39 | + print(f"{triplets.most_common()[0][0] = }") |
0 commit comments