For infinity, at least three loops are required. To do something flexible, it takes a ton of cycles. This example is a solution to Project Euler Problem 9 or more.
def fcount(start=1):
n = float(start)
while True:
yield n
n += 1
def find_triples():
for c in fcount():
for b in fcount():
if b > c:
break
for a in fcount():
if a > b:
break
if a ** 2 + b ** 2 == c ** 2:
yield (a, b, c)
def triples_by_sum(targetsum):
for a, b, c in find_triples():
if a + b + c == targetsum:
yield a, b, c
if c > targetsum:
break
if __name__ == '__main__':
for a, b, c in triples_by_sum(252):
print a, b, c
a, b, c = triples_by_sum(1000).next()
print a, b, c
for a, b, c in find_triples():
print a, b, c
Tyler lesmann
source
share