[Tutor] nested "for" loops

Adrian Maier am@fx.ro
Sat May 3 01:57:01 2003


Peter Jakubowicz (beyondthezero@earthlink.net) a scris :
> >>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)

> Thanks. Yes, I did run the program, which is what made me wonder is the 
> results were correct; I am trying to understand how nested loops work. I 
> get a list of triplets, but I was wondering how I could be sure that I'd 
> covered all of the possible combinations. I don't have a mental picture of 
> how or if this code runs through all the combinations of integers through 
> 20 and outputs all possible correct answers.

You could also try the following program. I've inserted a few "spies"
(the print commands) which will show you how does the program run:

max_number=3
for i in range(1, max_number):
     print "i=",i
     for j in range(1, max_number):
         print "    j=",j
         for k in range(1, max_number):
             print "       k=",k
             print "           checking if %d*%d + %d*%d = %d*%d"% (i, i, j, j, k, k)
             if (i * i) + (j * j) == (k * k):
                 print "           Pythagorean triple: %d, %d, %d" % (i, j, k)


Program output:

i=1
   j= 1
       k= 1
           checking if 1*1 + 1*1 = 1*1
       k= 2
           checking if 1*1 + 1*1 = 2*2
   j= 2
       k= 1
           checking if 1*1 + 2*2 = 1*1
       k= 2
           checking if 1*1 + 2*2 = 2*2
 i=2
    j= 1
       k= 1
           checking if 2*2 + 1*1 = 1*1
       k= 2
           checking if 2*2 + 1*1 = 2*2
    j= 2
       k= 1
           checking if 2*2 + 2*2 = 1*1
       k= 2
           checking if 2*2 + 2*2 = 2*2


If you set max_number to 21, you'll see for yourself that the program
tries all the (i,j,k) combinations.

I hope this helps.
         
-- 
Adrian Maier
(am@fx.ro)