Learn Python With Dhawal - Chapter 12- Sorting in Python


Before we begin the concepts about sorting there are few more concepts that I want to clear things about. Every language has some default parameters when a new variable is been created. In Java by default every number has value 0 or null for some others. In Python it would be always some or the other garbage value just like C. Also, when you are taking inputs some of the methods take inputs in very specific formats. For ex, the input() method takes everything as a string so when you want a number as input you need to convert it, or per say typecast it in technical terms.

We have seen a few examples of typecasting in previous coding examples where we have taken the input from the user for a calculator program and then typecasted the string input to integer format. If you don't take care of things like these, it might create issues in you programs. I can't possibly teach all the basics with the details here. This course is intended to keep a short informational aspect while exploring all the important topics. To dive into depth and learn more about it is your task.

A code might appear perfect on paper but it doesn't mean it is when you try on a computer.
For that you need to slowly explore the art of coding on your own and learn the art of debugging. Debugging can be done in various ways. For simplest you can put a print statement and see if some step is been executed or not. You can use console log commands if you know them.

Coming to Sorting, Python has various tools to make the work easy for you but unless you know how it works and how a sorting mechanism should behave, its of no use. So here we would explore a very basic sorting loop to understand how it would work.

Input :


  1. def sorting(a,l):
  2.     for i in a:
  3.         for i in range (1,l):
  4.             if(a[i-1]>a[i]):
  5.                 t=a[i-1]
  6.                 a[i-1]=a[i]
  7.                 a[i]=t


  8. l=int(input("Enter the size of list you want to sort.\n"))
  9. t=0
  10. a=[]
  11. for i in range (l):
  12.     a.append(int(input("Enter the element in list.\n")))
  13. print ("This is your entered list : ",a)
  14. sorting(a,l)
  15. print ("This is your sorted list : ",a)


Output :


  1. Enter the size of list you want to sort.
  2. 5

  3. Enter the element in list.
  4. 3

  5. Enter the element in list.
  6. 5

  7. Enter the element in list.
  8. 2

  9. Enter the element in list.
  10. 6

  11. Enter the element in list.
  12. 1
  13. This is your entered list :  [3, 5, 2, 6, 1]
  14. This is your sorted list :  [1, 2, 3, 5, 6]



Explanation :

As you noticed in first line, we defined the sorting function taking the two arguments a and l as a is the list of your elements and l is the length of that list.

I have given the option for used to define the length of the list but you can easily take a pre-defined list and use the method len() for getting the length of the list. but here for the fun of it, we are taking the list and elements both from the user.

There are 2 loops at step 2 and 3 if you notice. Inside the loop there's a swapping set of code which will swap the positions of 2 elements within the list if the previous one is larger than the later one. This way we will sort the list in an ascending order. Hence the inner for loop at step 3 would run once for the full length of the list to see if there are any abnormalities and every element satisfies the condition.

But we are just traversing the list once here. What if the list requires more than 1 run to sort the elements? Since there are 5 elements and taking an approximation that 5 is at a[0] and 1 is at a[l], this would be an worst case scenario. To sort the whole descending list into an ascending one, we would require to traverse the list lxl times to sort all the elements in ascending order.

Hence we set up a dual nested loop to traverse the list and sort all the elements. The number will only be swapped when the condition is true.

You can try some modifications on yourself to see how the code functions. To the result of the list after each inner for loop run you can print the list by adding print (a) command at step  8 to just see the swapped changes or to see every list after every iteration add the command at step 4.

Assignment:
I thought it would be a fun thing to let out a few things for you to try on your own. I want you to create a similar simple sorting program to sort things in a descending list. If you are successful in writing the code, do email me or just comment at let me know.

hint : use the '<' instead of '>' at step 4



I hope you enjoyed as much as I did writing this chapter. Here you learnt something more about loops, variables as well as functions in a gist and how to go about using them and build your own logic for various things as well as sorting the lists.

<< PREVIOUS CHAPTER || NEXT CHAPTER >>

~*~*~*~

This series is totally authored by me (Dhawal Joshi). Any similarities found on the text, or codes or anything is purely accidental. All the sources of reference will be mentioned, linked and will be given the proper credits. If I miss anything or there's anything wrong, feel free to comment or send me an email and I'll try to edit it out. I am not a Python expert, I am sharing whatever I have learnt on my own and with a few sources around to refer from which will be mentioned. Also feel free to share this series with others so most can benefit out of it.

~*~*~*~

Do comment and share your thoughts about it! I'd love to know what do you think. Also, I'd keep updating it quite often so do follow the Website to get all the updates by clicking here.

Also, a minor headsup.... Obsessed is free to read on Kindle Unlimited! Do check it out. I'd be glad to read your reviews!
Share :

Are you getting regular fresh content updates? If not click on the button below.

0 comments:

Post a Comment

Do comment and share your thoughts.