The first part of if
:
len( ) #1
set( ) #2
vec[i]+i for i in cols #3
Line 3 creates a iterator which returns the position value i
in the vec
plus the position value i
in cols
.
Line 2 converts line 3 into a set
, where there are no repeated values.
Line 1 picks up the length.
The second part follows the same logic, only changing from summing up for subtraction, and in the end compare the two.
vec[i]+i for i in cols
This line acts as a list understanding, with the difference that when not using keys ([]
) it creates an iterator.
A simple example of creating a list with understanding is:
lista = [x for x in range(10)]
That replaces:
lista = []
for x in range(10):
lista.append(x)
In the case of the doubt code it is passing two existing lists to create a third, the code for
alternative would be:
lista = []
for i in cols:
lista.append(vec[i]+i)
lista = set(lista)
lista = len(lista)
I had never seen this way (vec[i]+i for i in cols) of doing a for. It’s still a little obscure how I should interpret this, even with your explanation. Could you be more detailed? Thank you
– Leonardo Vinicius
hello, I edited my answer, I hope it makes sense
– Elton Nunes