How to perform variable assignment within nested loops in python list comprehension -


this question has answer here:

i learn how use list comprehension find things maximum value within matrix.

this simplified version of i'd do.

max_hourglass = 0 [[max_hourglass = i+j j in range(4) if j < 3] in range(4)] print(max) 

i syntax error assignment of max. tried casting i , j integers in case problem, however, doesn't appear case.

the more complicated problem i'm attempting use code solve hackerrank question. have solved it, however, attempting expand knowledge of python3 using different techniques solve problem. this hackerrank problem.

here more complicated problems code in case problem different it.

arr = [] _ in range(6):    arr.append([int(num) num in input().split()])  max_hourglass = 0 in range(4):     j in range(4):         hourglass = arr[i][j] + arr[i][j+1] + arr[i][j+2] + arr[i+1][j+1] + arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2]         if hourglass > max_hourglass:             max_hourglass = hourglass print(max_hourglass) 

as can see problem trying reduce list comprehension nested loops came code same logic simplified version:

[max_hourglass = (arr[i][j] + arr[i][j+1] + arr[i][j+2] + arr[i+1][j+1] + arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2]) j in range(4) if (arr[i][j] + arr[i][j+1] + arr[i][j+2] + arr[i+1][j+1] + arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2]) > max_hourglass] in range(4)] 

i'm aware less readable code , not use in production rather want further understand python's list comprehension syntax.

for context, hackerrank problem find in 2d array (matrix) largest sum of values made of shape i of denote hourglass shape.

e.g.

1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 2 4 4 0 0 0 0 2 0 0 0 0 1 2 4 0 

would result in output 19 values:

2 4 4   2   1 2 4 

add 19.

list comprehensions supposed used produce list. using them sort side effect discouraged. , in case of variable assignment, prohibited.

it in effect shorthand for

result = [] ...:     result.append(...) 

if problem not fit mold, has no business being written list comprehension.

it form construct several list comprehensions; , apply function max compress list 1 variable.

list1 = [.... in list0] list2 = [.... j in list1] mymax = max(list2) 

the lists replaced generators , dictionary comprehensions.

comprehensions encourage break calculation chunks or building blocks, strung more complicated operations.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -