How to improve this code? In C++ we use templates to write function for all data types. How to write such code in python?
def get_input(): #to get input from user
input_str = input("Enter elements to be sorted: ")
try:
lst = list(map(int, input_str.split())) #make a list of integers from input string
except:
raise TypeError("Please enter a list of integers only, seperated by a space!!")
return lst
def partition(thelist, start_idx, end_idx): #partition list according to pivot and return index of pivot
pivot = thelist[end_idx] #select last element as the pivot
idx = start_idx - 1
for curr_idx in range(start_idx, end_idx):
if thelist[curr_idx] <= pivot:
idx += 1
thelist[idx], thelist[curr_idx] = thelist[curr_idx], thelist[idx] #swapping
thelist[idx+1], thelist[end_idx] = thelist[end_idx], thelist[idx+1] #swapping
return idx+1 #returning pivot index
def quick_sort(thelist, start_idx, end_idx):
if len(thelist) == 0:
print("Empty list!!")
elif len(thelist) == 1:
print("Only one element!!")
elif start_idx < end_idx:
pivot_idx = partition(thelist, start_idx, end_idx) #get pivot index
quick_sort(thelist, start_idx, pivot_idx - 1) #apply algorithm for smaller list
quick_sort(thelist, pivot_idx + 1, end_idx) #apply algorithm for smaller list
if __name__ == '__main__':
input_list = get_input()
quick_sort(input_list, 0, len(input_list) - 1)
print(*input_list, sep = ", ")
-
1\$\begingroup\$ Why would you want to have typed versions of your sorting algorithm in the first place? \$\endgroup\$AlexV– AlexV2019年07月02日 07:36:25 +00:00Commented Jul 2, 2019 at 7:36
-
\$\begingroup\$ I am learning python and I think this is best to practice algorithms and to learn new language. \$\endgroup\$coder– coder2019年07月02日 08:38:07 +00:00Commented Jul 2, 2019 at 8:38
-
\$\begingroup\$ I don't know that much, I thought writing such programs will help me to learn python syntax and other functions available in Python. Should I not learn by writing such(Algorithms and Data Structures) programs? \$\endgroup\$coder– coder2019年07月02日 09:39:13 +00:00Commented Jul 2, 2019 at 9:39
-
\$\begingroup\$ @coder you can try PE or CodeAbbey or other sites to improve your skills. But it seems you are already good at it \$\endgroup\$camarman– camarman2019年07月03日 23:47:35 +00:00Commented Jul 3, 2019 at 23:47
-
\$\begingroup\$ What @Linny said. Also, I know it's a technicality, but a list with one or no elements is still technically sorted. \$\endgroup\$Confettimaker– Confettimaker2019年09月04日 04:41:30 +00:00Commented Sep 4, 2019 at 4:41
1 Answer 1
Docstrings
You should include a docstring
at the beginning of every function, class, and module you write. This will allow documentation to determine what your code is supposed to do.7
Variable Naming
Here is a list of variables/parameters that I would change. This increases readability, and makes the variables easier to understand.
input_str -> elements
thelist -> the_list
start_idx -> start_index
end_idx -> end_index
idx -> index
curr_idx -> current_index
A quick sentence about thelist
. You have been pretty consistent throughout your program, but remember all variables and parameter names are snake_case
.
Constants Naming
All constants in your program should be UPPER_CASE.
Operator Spacing
In python, and many other languages, we like to have our operators spaced out cleanly. They make the code easier to read and easier to comprehend. So when I see something like 1+1
, that's an instance red flag. You should separate this by having a space on either side of the operator, like 1 + 1
.
len(...) == 0
vs not ...
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
Yes: if not seq: if seq: No: if len(seq): if not len(seq):
print() vs quit()
You have a structure like so:
if len(thelist) == 0:
print("Empty list!!")
elif len(thelist) == 1:
print("Only one element!!")
elif start_idx < end_idx:
... run quick sort program ...
Instead of restricting running the quick sort program to an elif
, the first two checks should be separate if
s. Then, instead of using print(), use quit(). This will allow you to safely stop a program with a provided error message. Now, you can have the quick sort code run if the first two checks are false, like so:
if not the_list:
quit("Empty List!")
if len(the_list) == 1:
quit("Only one element!")
if start_idx < end_idx:
... run quick sort program ...
Parameter spacing
There should not be spaces separating an operator and a parameter name / value. Change this:
print(*input_list, sep = ", ")
to this:
print(*input_list, sep=", ")
Explore related questions
See similar questions with these tags.