[Tutor] nested "for" loops

John Miller jmillr@umich.edu
Mon May 5 17:28:02 2003


When I run this, I get:

 >>> limit = 20
 >>> [(x,y,z) for x in range(1,limit) for y in range(x,limit) for z in 
range (y,limit) if x*x + x*y == z*z]
[(4, 5, 6), (8, 10, 12), (12, 15, 18)]

These are not Pythagorean triples. Nevertheless, the code seems 
reasonable and I'm not sure why it isn't working. If I take Pan's 
solution and make a single change:

 >>> [(x,y, x*x+y*y) for x in range(1,21) for y in range(x,21) if 
(x*x+y*y) in [z*z for z in range(1,21)]]
[(3, 4, 25), (5, 12, 169), (6, 8, 100), (8, 15, 289), (9, 12, 225), 
(12, 16, 400)]

I get the non-duplicating results I want. BUT, I don't want z*z in the 
result set, I only want z. So if I do:

 >>> [(x,y,z) for x in range(1,21) for y in range(x,21) if (x*x+y*y) in 
[z*z for z in range(1,21)]]
[(3, 4, 20), (5, 12, 20), (6, 8, 20), (8, 15, 20), (9, 12, 20), (12, 
16, 20)]

Here, 'z' is always at the end of the range operation. It seems as 
though some blend of Bob and Pan's one-liners ought to generate 
non-duplicating triples (without using the sqrt() function), but the 
syntax is eluding me...

(Also, I'm still wondering why the earlier code I posted generates the 
'''RuntimeError: maximum
recursion depth exceeded''' error.)

John Miller

On Monday, May 5, 2003, at 04:07 PM, Bob Gailer wrote:

> You can take the solution for non-duplicated results that I posted and 
> turn it into a comprehension:
>
> limit = 20
> [(x,y,z) for x in range(1,limit) for y in range(x,limit) for z in 
> range (y,limit) if x*x + x*y == z*z]