[Tutor] nested "for" loops
Bob Gailer
bgailer@alum.rpi.edu
Fri May 2 23:43:02 2003
--=======39571A28=======
Content-Type: text/plain; x-avg-checked=avg-ok-25011F82; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit
At 07:43 PM 5/2/2003 -0700, Peter Jakubowicz wrote:
>Hi,
>
>I've been slogging along learning Python for a while now. Nested "for"
>loops confuse me (I have trouble trying to run through them in my head).
>For example, does the following code generate (albeit redundantly) all
>Pythagorean triples up to 20: i.e., all integers less than or equal to 20
>for which i * i + j * j == k * k
>
>TIA,
>Peter
>
>
>
>for i in range(1, 21):
> for j in range(1, 21):
> for k in range(1, 21):
> if (i * i) + (j * j) == (k * k):
> print "Pythagorean triple: %d, %d, %d" % (i, j, k)
Did you run the program? Did it deliver the desired results? There's your
answer. Is that what you wanted to know? Or are you needing a way to
comprehend nested loops?
BTW it's a good idea to anticipate performance and maintenance issues,
especially if you wanted to expand this to a higher limit. Suggestion -
move the calculation of i*i and j*j out of the inner loop. Right now these
calculations are unnecessarily repeated. Also make the limit a variable
whose value you set once. Then it's a lot easier to change the limit. Also
to eliminate duplications start each inner loop with the current value of
the next higher loop.
limit = 21
for i in range(1, limit ):
iSq = i*i
for j in range(i, limit ):
jSq = j*j
for k in range(j, limit ):
if iSq+ jSq == (k * k):
print "Pythagorean triple: %d, %d, %d" % (i, j, k)
Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
--=======39571A28=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-25011F82
Content-Disposition: inline
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.474 / Virus Database: 272 - Release Date: 4/18/2003
--=======39571A28=======--