3
\$\begingroup\$

I am a beginner in python and to learn python I have written this program. How can this code be improved? Should I use main method in this program? Python

lst = []
def insertion_sort(thelist):
 for index in range(1, len(thelist)):
 key = thelist[index]
 position = index - 1
 while position >= 0 and thelist[position] > key:
 thelist[position + 1] = thelist[position]
 position = position - 1
 thelist[position + 1] = key
n = int(input("Enter number of elements: "))
for i in range(0, n):
 ele = int(input())
 lst.append(ele)
insertion_sort(lst)
print(*lst, sep = ", ")
MrJoe
2,16312 silver badges30 bronze badges
asked Jun 25, 2019 at 9:37
\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

There is a much simpler method in Python to do an insertion sort using the bisect.insort method

import bisect
array = [1,3,5,7]
bisect.insort_left(array, 2)
>>[1, 2, 3, 5, 7]

With regard to your coding style, I would recommend using the if __name__ == "__main__" guard.

You can also just say for i in range(n) with no need to say (0, n)

You can also use list-comprehension to build the list:

import bisect
def insertion_sort(thelist):
 new_list = []
 for item in thelist:
 bisect.insort_left(new_list, item)
 return new_list
if __name__ == "__main__":
 n = int(input("Enter number of elements: "))
 lst = [input("Please enter a number: ") for i in range(n)]
 new_list = insertion_sort(lst)
 print(*new_list, sep = ", ")
answered Jun 25, 2019 at 10:21
\$\endgroup\$
1
\$\begingroup\$
  • Try to make functions for every logical thing you do like getting the elements. use def get_input()

  • Use if __name__ == "__main__" guard. It is a good practice when you are importing this program to another program, it will not run the code in this program entirely.

  • There is no need to use a for loop for getting the list you can use split() on the entire input which would create a list as desired. It is pythonic to use split().

  • There is no need to make n as lists in python are dynamic. You can get the length in O(1) time using len(lst).

  • Name your variables clearly, slightly longer names are not a problem. lst would be input_list etc.

  • You can use enumerate in for index in range(1, len(thelist)):. Which would give the index and elements of the list. More pythonic.

answered Jun 25, 2019 at 12:58
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.