## Python Pythagorean Triple Generator

For some crazy reason, I have spent significant amounts of time rediscovering a method of generating all possible primitive Pythagorean triples. After proving that the following works, I decided to check Wikipedia. Oh, well.

def rationals(): x,y = 1,1 while True: yield x,y x,y = y, (2*(x//y) + 1)*y - x def odds(): for x,y in rationals(): if x % 2: yield x,y def triplets(): for x,y in odds(): r,s,t = x**2, 2*x*y, 2*y**2 yield r+s, s+t, r+s+t if __name__ == "__main__": for trip in triplets(): print trip

Advertisements

What is your reasoning for generating x and y that way?

Anonymous6 Oct 2013 at 5:24 pm

The

`rationals()`

function produces (numerator, denominator) tuples from the Calkin–Wilf sequence, iterating through all of the rational numbers exactly once each. This is not a trivial iteration, it essentially takes all pairs of positive integers and throws out everything that has a greatest common divisor greater than one. That becomes important in`triplets()`

because such pairs don’t form primitive triplets, and therefore duplicate triplets generated by other pairs. On the other hand, if you don’t mind duplicates, then a simpler way to generate number pairs would still generate valid triplets.eswald8 Oct 2013 at 8:43 pm