0

I was solving a problem on Hackerrank named "2d hourglass", i was unable to solve the problem, i searched their forums and found the solution, but I am unable to understand the solution

def hourglassSum(arr):
    return(max([sum(arr[i][j:j+3] + [arr[i+1][j+1]] + arr[i+2][j:j+3]) for i in range(4) for j in range(4)]))

and also please explain me how the for loop at end works I am not accustomed to such implementation of for loop generaly I approach the for loops in this way:-

for i in range(4):
   for j in range(4):

I only understand the working for loop when implemented in above mentioned way, I have stumbled upon many coded where for loops are in the end and I have never been able to understand them

Victor Dorian
  • 11
  • 1
  • 1
  • 4
  • 1
    Possible duplicate of [Explanation of how nested list comprehension works?](https://stackoverflow.com/questions/20639180/explanation-of-how-nested-list-comprehension-works) – Nir Alfasi Jun 06 '19 at 06:23
  • Also: https://stackoverflow.com/questions/51861577/python-list-function-or-list-comprehension/51861670 – Nir Alfasi Jun 06 '19 at 06:24
  • I understand that, yet not able to understand the working of each iterations – Victor Dorian Jun 06 '19 at 06:48
  • Also: https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it – Nir Alfasi Jun 07 '19 at 15:51

1 Answers1

0

This is just syntactic sugar called list comprehension. In essence, the inline for loops are nested for loops just like you described above.