Skip to main content
5 of 6
faster? since when do we care about fast in code golf? ;)
pxeger
  • 25.3k
  • 4
  • 59
  • 146

Collapse two numerical loops into one

Say you're iterating over the cells of an m*n grid. Instead of two nested for loops, one for the row and one of the columns, it's usually shorter to use a single loop to iterate over the m*n cells of the grid. You can extract the row and column of the cell inside the loop.

Original code:

for i in range(m): for j in range(n): do_stuff(i,j) 

Golfed code:

for k in range(m*n): do_stuff(k/n,k%n) 

In effect, you're iterating over the Cartesian product of the two ranges, encoding the pair (i,j) as x=i*n+j. You've save a costly range call and a level of indentation inside the loop. The order of iteration is unchanged.

Use // instead of / in Python 3. If you refer to i and j many times, it may be shorter to assign their values i=k/n, j=k%n inside the loop.

xnor
  • 149.7k
  • 26
  • 287
  • 676