Python Implementation of Problem 9
View source code here on GitHub!
Includes
Problem Solution
Project Euler Problem 9
My triples() function is definitely pythonic, but I don't know if it is all that efficient. I feel like I could do better.
Problem:
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a**2 + b**2 = c**2
For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.
1"""
2Project Euler Problem 9
3
4My triples() function is definitely pythonic, but I don't know if it is all
5that efficient. I feel like I could do better.
6
7Problem:
8
9A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
10a**2 + b**2 = c**2
11
12For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2.
13
14There exists exactly one Pythagorean triplet for which a + b + c = 1000.
15Find the product abc.
16"""
17from functools import reduce
18from itertools import count
19from operator import mul
20from typing import Iterator, Tuple
21
22
23def triples() -> Iterator[Tuple[int, int, int]]:
24 for c in count(3):
25 for b in range(2, c):
26 for a in range(1, b):
27 if a**2 + b**2 == c**2:
28 yield (a, b, c)
29
30
31def main() -> int:
32 for triple in triples():
33 if sum(triple) == 1000:
34 return reduce(mul, triple, 1)
35 return -1 # pragma: no cover