Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to nesting for loops in Python

I've read that one of the key beliefs of Python is that flat > nested. However, if I have several variables counting up, what is the alternative to multiple for loops? My code is for counting grid sums and goes as follows:

def horizontal():
    for x in range(20):
        for y in range(17):
            temp = grid[x][y: y + 4]
            sum = 0
            for n in temp:
                sum += int(n)
            print sum # EDIT: the return instead of print was a mistype

This seems to me like it is too heavily nested. Firstly, what is considered to many nested loops in Python ( I have certainly seen 2 nested loops before). Secondly, if this is too heavily nested, what is an alternative way to write this code?

like image 246
davenz Avatar asked Dec 17 '12 05:12

davenz


People also ask

What can I use instead of a for loop?

> filter() The most common way was to use for loop, iterate elements and find which is even. Instead of using for in this case, we can use the filter() method. This method also returns a new array.

Should you avoid nested for loops?

Nested loops are frequently (but not always) bad practice, because they're frequently (but not always) overkill for what you're trying to do. In many cases, there's a much faster and less wasteful way to accomplish the goal you're trying to achieve.

Can you only nest for loops?

The placing of one loop inside the body of another loop is called nesting. When you "nest" two loops, the outer loop takes control of the number of complete repetitions of the inner loop. While all types of loops may be nested, the most commonly nested loops are for loops.


2 Answers

from itertools import product

def horizontal():
    for x, y in product(range(20), range(17)):
        print 1 + sum(int(n) for n in grid[x][y: y + 4])

You should be using the sum function. Of course you can't if you shadow it with a variable, so I changed it to my_sum

like image 93
John La Rooy Avatar answered Oct 11 '22 13:10

John La Rooy


grid = [range(20) for i in range(20)]
sum(sum( 1 + sum(grid[x][y: y + 4]) for y in range(17)) for x in range(20))

The above outputs 13260, for the particular grid created in the first line of code. It uses sum() three times. The innermost sum adds up the numbers in grid[x][y: y + 4], plus the slightly strange initial value sum = 1 shown in the code in the question. The middle sum adds up those values for the 17 possible y values. The outer sum adds up the middle values over possible x values.

If elements of grid are strings instead of numbers, replace
sum(grid[x][y: y + 4])
with
sum(int(n) for n in grid[x][y: y + 4]

like image 20
James Waldby - jwpat7 Avatar answered Oct 11 '22 14:10

James Waldby - jwpat7