Euler Project: Problem 9 – Python

The Euler Project has been a fun way to examine how well we know our programming language of choice. Today we’re covering problem 9 which reads as follows:

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.

So this was an interesting one. I decided to have some fun with list comprehension, even though i think there is probably a faster more efficient way of doing this, but I was laughing with some colleagues about how many things can be solved in one line in python, when I went home I started on this problem, and decided, hell, lets go for it in one line (ish, i like to have a run() function just a means of managing my files, but it really isn’t needed for the solution) . Also, we could sub out of def create_pythag() function for an in-line lambda, but i didn’t, and should have. Here’s the code:

1
2
3
4
5
6
def create_pythag(a,b):
	return a*b*(1000-b-a)
 
def run():
	result = [create_pythag(a,b) for a in range(1,498) for b in range(1,498) if ((a*a)+(b*b)) == ((1000-b-a)*(1000-b-a))]
	print result[0]

Yay for nested for loops in list comprehension. The for a in.. for b in.. is like a nested for loop. as an example if i entered
in the console.. [[a,b] for a in range(1,10) for b in range (1,10)], it would spit out a list of lists like:
[[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [1, 7], [1, 8], [1, 9], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [2, 9], [3, 1], [3, 2], [3, 3], [3, 4], [3, 5], [3, 6], [3, 7], [3, 8], [3, 9], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [4, 9], [5, 1], [5, 2], [5, 3], [5, 4], [5, 5], [5, 6], [5, 7], [5, 8], [5, 9], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [6, 7], [6, 8], [6, 9], [7, 1], [7, 2], [7, 3], [7, 4], [7, 5], [7, 6], [7, 7], [7, 8], [7, 9], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6], [8, 7], [8, 8], [8, 9], [9, 1], [9, 2], [9, 3], [9, 4], [9, 5], [9, 6], [9, 7], [9, 8], [9, 9]]
So that’s how were getting all the possible combos up to 498. Why 498? Well stupid (just kidding, we love you), its because we know a and b have to be lower than c, and the sum of all of them have to equal 1000, so if either a or b IS 500, c will have to be greater than, and thus definitely not equal 1000. Really, we can use common sense to adjust the numbers – i just made sure they were less than 500 here. We then have the conditional added to the comprehension that simply requires, only append when a^2 plus b^2 == c^2 where a+b+c = 1000. We do this by having the 1000-b-a do our a+b+c= 1000 check, and just having a simple comparison of squares. Hope you enjoyed our view on the Euler Project problem number 9, we look forward to hearing your thoughts on these problems, and any other solutions you came up with!

Comments

No Comments

Leave some