This code works, and I'm trying to figure out if there's a better way to optimize it. As you can see, I've cut down drastically on time just by using numbers that work for a < b < c. Is there any outstanding thing that can reduce the time? It currently takes ~7 seconds.
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\$.
My code:
import time
start = time.time()
def pythag(a, b, c):
if a ** 2 + b ** 2 == c ** 2:
return True
return False
a = [x for x in range(1, 1000)]
for num in a:
for dig in range(num, 1000 - num):
for i in range(dig, 1000 - dig):
if num + dig + i == 1000:
if pythag(num, dig, i):
print(num, dig, i)
print("Product: {}".format(num * dig * i))
elapsed = time.time() - start
print("Time: {:.5f} seconds".format(elapsed))
exit(1)
# 200 375 425
# Product: 31875000
# Time: 7.63648 seconds