About the structure of the 'sorted' function, how does it work?

The statement below is made as many times as the size of the Vector sub. What is the result of this instruction?

sorted(sub, key = lambda x : size(x) )

Where x are the values from 0 to 31 inclusive and where sub is an array of this genus

sub = [0,1,2,3, (...), 30, 31]

And size is this function:

def size(int_type):
   length = 0
   count = 0
   while (int_type):
       count += (int_type & 1)
       length += 1
       int_type >>= 1
   return count
Author: Woss, 2018-12-03

1 answers

This calling the function sorted() which will sort the elements of the list sub that you know what it is. What you probably don't know is the argument calling key.

If you don't know this, I say it's a named argument, which is different from the arguments we normally use that is identified by the position it is used, so it would be the first argument thrown into the variable of the first parameter of the function called, and the second goes to the second parameter and so on. It does not matter what position you are in, you say its name, but the great advantage is that it better documents what you are doing, in which case it is indicating how the classification key should be composed.

Here Comes the other thing you may not know is that the lambda . It is a way to define a very simple algorithm, more or less like you do in a function, but it will not run as it normally does with normal functions. You are passing the algorithm as argument, who will execute this algorithm is the inner part of the function sorted(). Then there the classification will occur according to the result of the function size(), in each element of the list sub there will be an interaction and during the classification the element of that interaction will be passed as argument to the lambda, so this value will be received in x and this will be used as argument in the function size().

As far as I understand the function size() picks up how many connected bits it has in the past number, up to find the first 0. The algorithm has an unused variable, something tells me that it does not do what is expected.

A lambda is a way for you to slow down the execution of an algorithm that needs to be defined at that time.

If you want to understand more about lambda , you can read another answer in another language, but the concept is the same, and there are links there for other answers that help

 4
Author: ,