updated the code for better understanding: added alternative method for quick sort and added description for some lines of code

This commit is contained in:
K 2023-12-10 19:32:22 +05:30
parent 6db1cebae8
commit a78f6deacc
Signed by: notkshitij
GPG Key ID: C5B8BC7530F8F43F

View File

@ -1,31 +1,50 @@
# BEGINNING OF CODE
# Function for quick sort: # Function for quick sort:
def quicksort(arr): def quickSort(arr):
if len(arr) <= 1: if len(arr) <= 1: # if array is empty array
return arr return arr
pivot = arr[len(arr) // 2] pivot = arr[len(arr) // 2] # Set pivot element
left = [x for x in arr if x < pivot] left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot] middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot] right = [x for x in arr if x > pivot]
'''
## ALTERNATIVE WAY OF WRITING THE UPPER 3 LINES (for easy understanding)
left = [] # Empty list to store left part
for i in arr:
if (i < pivot):
left.append(i)
middle = [] # Empty list to store middle element
for i in arr:
if (i == pivot):
middle.append(i)
right = [] # Empty list to store right part
for i in arr:
if (i > pivot):
right.append(i)
'''
return quicksort(left) + middle + quicksort(right) return quickSort(left) + middle + quickSort(right)
# Function for displaying top scores: # Function for displaying top scores:
def top5(arr): def top5(arr):
sorted_arr = quicksort(arr) top_scores = quickSort(arr)
top_scores = sorted_arr[-5:][::-1] return top_scores[-1:-6:-1]
return top_scores
# Defining main function: # Defining main function:
def main(): def main():
total=int(input("Total number of students are:\t")) percent = [] # List to store percentages
percent=[]
total = int(input("Total number of students are:\t")) # Input for total students
for i in range(total): for i in range(total):
percent_in = float(input(f"Enter percentage for student {i+1}:\t")) percent_in = float(input(f"Enter percentage for student {i+1}:\t"))
percent.append(percent_in) percent.append(percent_in)
print(f"\nPercentages of students are:\t {percent}")
print(f"\n------------------\nSorted marks (using quick sort algorithm):\t{quicksort(percent)}\n------------------") print(f"-----\nPercentages of students are:\t {percent}\n-----")
print(f"\n------------------\nTop five scores are:\t{top5(percent)}\n------------------\n") print(f"\n-----\nSorted marks (using quick sort algorithm):\t{quickSort(percent)}\n-----")
print(f"\n-----\nTop five scores are:\t{top5(percent)}\n-----")
# Calling main function: # Calling main function:
main() main()
# END OF CODE