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
Advertisement