0

I came across this code on selection sort algorithm:

ls = [2, 5, 1, -9, 10, 13, 7, 2]


def selection_sort(ls):
      for i in range(len(ls)):
         imin = min(range(i,len(ls)), key = lambda x: ls[x])
         ls[i], ls[imin] = ls[imin], ls[i]

I know the typical selection_sort with the if block, but this one is hard to understand. I tried to print imin with all possible i's and the result was 33337777 which doesn't make sense to me. I think my problem is that I don't know how this specific key works. Does anyone have any insight on this?

9
  • 1
    How can one understand a particular value during execution w/o knowing what the input to the function was? Commented Aug 18, 2022 at 12:06
  • Can you explain what you do understand about this code? Commented Aug 18, 2022 at 12:06
  • @khelwood thank you for the edit, im new to stack overflow, i really dont know how to construct everything in the right way. Commented Aug 18, 2022 at 12:19
  • @KellyBundy no im sorry, i tried for i in range(len(ls)): imin = min( range(i,len(ls)), key= lambda x: ls[x]) print(imin) , to make the problem simpler and try to understand the code. Commented Aug 18, 2022 at 12:29
  • @KellyBundy "are we supposed to believe" man, why such an irony for someone who literally codes for 1 week? If you cant be patient with my bad format of the question, you dont have to answer Commented Aug 18, 2022 at 12:34

1 Answer 1

0

function declaration

The statement is the function definition, Which takes one argument i.e. list

def selection_sort(ls):

Loop Initialization

A for-loop is defined that will iterate the list from i = 0 to the len(ls).

for i in range(len(ls)):

Main Logic

Inside the for-loop, there are 2 statements

imin = min(range(i,len(ls)), key = lambda x: ls[x])

The above code uses python's min function taking 2 arguments, an iterator and a function to find the minimum value from the list starting from index i to len(ls) and return the item's index using the lambda function passed as the second argument.

ls[i], ls[imin] = ls[imin], ls[i]

The above code is responsible for swapping the minimum item with the item at the index i of the list.

Sign up to request clarification or add additional context in comments.

3 Comments

thank you for the great answer ill read it and try to understand where my problem was. Thank you also for not paying attention to my bad format and you werent ironic or elitist towards me.
So all in all imin returns ls[x] , that's what lambda x: ls[x] does right? I think i get it now! thank you @Sidharth Mudgil
of course it did

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.