Discussion Room : IDC101

A question for all

A question for all

by Dr. Amit Kulshrestha -
Number of replies: 10

What does this function do? Why does it work?

def f(L):
    size = len(L)
    M = []
    for i in range(size):
        m = min(L)
        M.append(m)
        i = 0
        while L[i] != m:
            i = i + 1
        del L[i]
    return M
In reply to Dr. Amit Kulshrestha

Re: A question for all

by Dheer Mankad . -

It returns a sorted list. It makes another list by taking elements from the given list in ascending order. Once the minimum of the list is taken, it deletes that element from the list and then again finds the minimum. The loop goes on until we make a new list.

In reply to Dr. Amit Kulshrestha

Re: A question for all

by Suroj Dey -

It returns a sorted list in ascending order.

It declares an empty list M, which then is appended with the minimum value of the original list using min(), the element is then deleted from the original list, as the iteration goes, M is appended with second smallest and 3rd smallest, so on and so forth, until an ascended ordered list is obtained.

In reply to Dr. Amit Kulshrestha

Re: A question for all

by Arkopal Nandy . -

It returns a sorted list in ascending order. There is an old list and a new empty list M is created. The minimum element from the old list is removed and is then appended into the new list. Similarly, the 2nd smallest and 3rd smallest elements of L are so on appended into the new list M. As the elements are appended into the new list, they are simultaneously removed from the old one.

This process continues till all elements of L are removed. As a result L is empty list now and M has been converted into a sorted list in which all the elements are in ascending order.

In reply to Dr. Amit Kulshrestha

Re: A question for all

by Dr. Amit Kulshrestha -

I am happy that Dheer, Suroj and Arkopal have given the right answer.

Now the point is, how to find min or max in a list?

Can someone suggest a way to achieve this with minimum number of comparisons?


In reply to Dr. Amit Kulshrestha

Re: A question for all

by Suroj Dey -

Let 

min = List[0], i.e the starting element of a list

for i in range(len(mylist)):

if ( min>list[i])

Swap min with list[i]

"

min,list[i]=list[i],min

................

at the end of the loop, min will be modified to the least element of the list.

For Max, similar argument holds.

In reply to Suroj Dey

Re: A question for all

by Kapil Paranjape -

Why swap? Swapping is not required!

In reply to Kapil Paranjape

Re: A question for all

by Suroj Dey -
Yes, I was wrong, swapping was not needed, my bad!.

@Gariman- You're correct!