List comprehensions: Difference between revisions

Content added Content deleted
Line 1,686: Line 1,686:


<lang python>((x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2)</lang>
<lang python>((x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2)</lang>

A slower but more readable version:

<lang python>[(x, y, z) for (x, y, z) in itertools.product(xrange(1,n+1),repeat=3) if x**2 + y**2 == z**2 and x <= y <= z]</lang>

Or as an iterator:

<lang python>((x, y, z) for (x, y, z) in itertools.product(xrange(1,n+1),repeat=3) if x**2 + y**2 == z**2 and x <= y <= z)</lang>

Alternatively we shorten the initial list comprehension but this time without compromising on speed. First we introduce a generator which generates all triplets:

<lang python>def triplets(n):
for x in xrange(1, n + 1):
for y in xrange(x, n + 1):
for z in xrange(y, n + 1):
yield x, y, z</lang>

Apply this to our list comprehension gives:

<lang python>[(x, y, z) for (x, y, z) in triplets(n) if x**2 + y**2 == z**2]</lang>

Or as an iterator:

<lang python>((x, y, z) for (x, y, z) in triplets(n) if x**2 + y**2 == z**2)</lang>


=={{header|R}}==
=={{header|R}}==