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,828
  • 2
  • 19
  • 28
  • Use numpy library Take a look at that question http://stackoverflow.com/questions/211160/python-inverse-of-a-matrix – Rami Mar 07 '14 at 05:40
  • It might be helpful to get an answer if you can simplify your question a bit – zhangxaochen Mar 07 '14 at 05:41
  • Give a complete example, with values for `kt` and `k`. – U2EF1 Mar 07 '14 at 06:07
  • @U2EF1 for example kt=[1,1,1],and k is a 3x3 matrix which will be got in the program – maple Mar 08 '14 at 12:57
  • Evidently, using Tree-like structures & algorithms are better for such a task, vectorization of a matrix can adds to speed of execution, parallel execution also is usefull to implement in such a case... but for beautiful solution - better create algorithm first not concerning your data – JeeyCi Jul 31 '23 at 05:11

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,419
  • 2
  • 23
  • 24