Posts Tagged ‘prob9’

Problem 9

June 12, 2009

I didn’t feel right letting the week go by with no solutions posted, so I rigged one up for problem 9 (find the unique Pythagorean triple which sums to 1000). To generate Pythagorean triples, I used what is identified as Euclid’s Formula on the Wikipedia page for Pythagorean triples. After a little while, I decided the appropriate generalization of this problem was to take in any number, and find all of the Pythagorean triples that sum to the given number. Here’s what I came up with:

import sys
goal = len(sys.argv) >= 2 and int(sys.argv[1]) or 1000

answers = []

for n in xrange(1,goal):
    for m in xrange(n+1,goal,2):
        a,b = 2*m*n,m*m-n*n
        trip = (min(a,b),max(a,b),m*m+n*n)
        s = sum(trip)
        if(goal % s == 0):
            k = goal // s
            trip = map(lambda x:k*x,trip)
            if not (trip in answers):
                answers.append(trip)

I’m fairly certain that the loops could be cut down in size, but I’m a bit tired right now to see exactly how far. I increment m by 2 because it keeps the parity of m and n different, which Wikipedia claims is a requirement to generate a “primitive” triple.

I keep hoping to find a function that will take a list, and return just the unique objects from that list, but have yet to run across it. It’d just about work to make a set of the objects, but apparently “list objects are unhashable”, and so doing sets of tuples doesn’t go like I expect it to. Probably because I haven’t read enough, or thought quite enough about what is going on. Maybe one of these days I’ll get it.

Advertisements