Minority Opinions

Not everyone can be mainstream, after all.

Python Pythagorean Triple Generator

with 2 comments

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

Written by eswald

25 Feb 2010 at 10:24 am

Posted in Python

2 Responses

Subscribe to comments with RSS.

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


    6 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.


      8 Oct 2013 at 8:43 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s