TheAlgorithms-Python
55 строк · 1.7 Кб
1"""
2Problem 39: https://projecteuler.net/problem=39
3
4If p is the perimeter of a right angle triangle with integral length sides,
5{a,b,c}, there are exactly three solutions for p = 120.
6{20,48,52}, {24,45,51}, {30,40,50}
7
8For which value of p ≤ 1000, is the number of solutions maximised?
9"""
10
11from __future__ import annotations12
13import typing14from collections import Counter15
16
17def pythagorean_triple(max_perimeter: int) -> typing.Counter[int]:18"""19Returns a dictionary with keys as the perimeter of a right angled triangle
20and value as the number of corresponding triplets.
21>>> pythagorean_triple(15)
22Counter({12: 1})
23>>> pythagorean_triple(40)
24Counter({12: 1, 30: 1, 24: 1, 40: 1, 36: 1})
25>>> pythagorean_triple(50)
26Counter({12: 1, 30: 1, 24: 1, 40: 1, 36: 1, 48: 1})
27"""
28triplets: typing.Counter[int] = Counter()29for base in range(1, max_perimeter + 1):30for perpendicular in range(base, max_perimeter + 1):31hypotenuse = (base * base + perpendicular * perpendicular) ** 0.532if hypotenuse == int(hypotenuse):33perimeter = int(base + perpendicular + hypotenuse)34if perimeter > max_perimeter:35continue36triplets[perimeter] += 137return triplets38
39
40def solution(n: int = 1000) -> int:41"""42Returns perimeter with maximum solutions.
43>>> solution(100)
4490
45>>> solution(200)
46180
47>>> solution(1000)
48840
49"""
50triplets = pythagorean_triple(n)51return triplets.most_common(1)[0][0]52
53
54if __name__ == "__main__":55print(f"Perimeter {solution()} has maximum solutions")56