I am new to python and I have a question
A = [3,2,4,1]
N = len(A)
B = sorted(range(N), key = lambda i: A[i])
print(B)
output #[3, 1, 0, 2]
input #A = [7,2,4,1]
output #[3, 1, 2, 0]
I do not understand the output ?? Can anyone explain to me?
I am new to python and I have a question
A = [3,2,4,1]
N = len(A)
B = sorted(range(N), key = lambda i: A[i])
print(B)
output #[3, 1, 0, 2]
input #A = [7,2,4,1]
output #[3, 1, 2, 0]
I do not understand the output ?? Can anyone explain to me?
Let's talk about the specific example you have used
A = [3, 2, 4, 1]
N = len(A) . # N = 4
B = sorted(range(N), key = lambda i: A[i]) # sorted([0,1,2,3], key= lambda i:A[i])
Basically you are trying to sort [0,1,2,3] based on the values A[i] which are [3,2,4,1]
Now, A[3] < A[1] < A[0] < A[2]
And so you get the answer as [3, 1, 0, 2]
In the sorted
function the first element is the item you would like to sort. If you can you sort a generator that is converted to a list of size 4. The sorting function sorts according to the value given by the anonymous function.
In your case - A = [3, 2, 4, 1]
List to sort - [0, 1, 2, 3]
. Keys for each element [3, 2, 4, 1]
. Basically you can imagine you sort [(0, 3), (1, 2), (2, 4), (3, 1)]
according to the second element and then left with the first element and this results [3, 1, 0, 2]
you get.