How to read the following code in python?

Asked

Viewed 82 times

0

I found a code in Python, but I’m not getting how it works.

from itertools import permutations

n = 8
cols = range(n)
contador = 0

for vec in permutations(cols):
    if n == len(set(vec[i]+i for i in cols)) == len(set(vec[i]-i for i in cols)):
        print ( vec )

Until the for I understood, but in the if got lost.

1 answer

2


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

  • hello, I edited my answer, I hope it makes sense

Browser other questions tagged

You are not signed in. Login or sign up in order to post.