I'm using Python 3 and have written this code to find the right triangle sides when given the perimeter:
def intRightTri(p):
l = [(a,b,c) for a in range (1, p)
for b in range (1, p)
for c in range (1, p)
if (a**2 + b**2 == c**2) and (a + b + c == p) and (a<=b) and (b<c)]
return l
When I run my tests, they work, but the last one seems to be taking a really long time. What would be a good way to improve my code so it executes quicker?
import unittest
tc = unittest.TestCase()
tc.assertEqual(intRightTri(100), [])
tc.assertEqual(intRightTri(180), [(18, 80, 82), (30, 72, 78), (45, 60, 75)])
tc.assertEqual(intRightTri(840),
[(40, 399, 401),
(56, 390, 394),
(105, 360, 375),
(120, 350, 370),
(140, 336, 364),
(168, 315, 357),
(210, 280, 350),
(240, 252, 348)])
Update
New quicker method combining both answers.
def integer_right_triangles(p):
l = [(a,b,p-a-b) for a in range (1, p)
for b in range (a, p-a)
if (a**2 + b**2 == (p - (a+b))**2 )]
return l