The ultimate efficience

--Originally published at Fundamentos de Programación

RAMDOM, the worst way to sort a list of numbers.

pdwbyrk_700w_0

Well, I had to sort a list of n numbers for the challenge, thanks Ken!

And, what is the problem?

nwrlojr_700wa_0

Yes, there is a huge problem: it’s really inefficient.

krp0arl_700wa_0

But well, the point of the challenge was for us to realice this. So this is what I did:

sorted1

First things first. We import the main character here: random. After that we have the function that checks if the list is sorted and returns the boolean value True if the list is in order or False if the list is not in order, we are sorting the list high to low.

odgoegd_700wa_0

The user is asked how many numbers does he/she wants to sort and then proceeds to ask the user for those numbers which are stored in a list using the for.

3dbolpw_700wa_0

We rearrange the list giving random indexes to the numbers and creating a new list. Then we run the function is_sorted() again and again until it returns the value True (when the list is in order).

We print the list in order and the amount of times it took random to get it right. Here is an example:

sort2

sort3

As you can see it took 138 tries to sort only 5 numbers!

What you learn with this is to not use random to get things in order…

Here you have the worst of the worst… sort 10 numbers:

1rxbzwp_700wa_0

Keep up with the code:

Follow me on twitter @danigguemez

Get the code in github: https://github.com/Guemez/TC1014/blob/master/sortednumbers.py

#TC101 #Python #DailyChallenge #Random #3milliontries