1

I am writing a program in python which contains six loops. The program gives all the combination of a 3x3 matrix of which each row add up to kt[i]. I wonder whether there are any optimization of this program to reduce the loops for it is not very good to use too many loops nested together.

for r0 in range(0,kt[0]+1):
    for s0 in range(0,kt[0]+1-r0):
        k[0]=[r0,s0,kt[0]-r0-s0]
        for r1 in range(0,kt[1]+1):
            for s1 in range(0,kt[1]+1-r1):
                k[1]=[r1,s1,kt[1]-r1-s1]
                for r2 in range(0,kt[2]+1):
                    for s2 in range(0,kt[2]+1-r2):
                        k[2]=[r2,s2,kt[2]-r2-s2]
                        do something here
maple
  • 1,710
  • 2
  • 17
  • 26

1 Answers1

0

How about using itertools.permutations?

import itertools

elems = range(4)
for row1 in itertools.permutations(elems, 3):
   for row2 in itertools.permutations(elems, 3):
      for row3 in itertools.permutations(elems, 3):
         print '{}\n{}\n{}\n{}'.format(row1, row2, row3, '-'*80)
      print '='*80
Wojciech Walczak
  • 3,130
  • 2
  • 23
  • 23