davenz - 1 month ago 19

Python Question

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?

Answer

```
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`

Source (Stackoverflow)

Comments