Need help writing this program in Python. Write a program to input 5 names and r
ID: 3572503 • Letter: N
Question
Need help writing this program in Python.
Write a program to input 5 names and reorder them alphabetically, and output them. To do so, follow this "recipe" for your calculations code block: if the first name is greater than the second name, swap them. if the first name is greater than the third name, swap them. if the first name is greater than the fourth name, swap them. if the first name is greater than the fifth name, swap them. if the second name is greater than the third name, swap them. if the second name is greater than the fourth name, swap them. if the second name is greater than the fifth name, swap them. if the third name is greater than the fourth name, swap them. if the third name is greater than the fifth name, swap them. if the fourth name is greater than the fifth name, swap them.Explanation / Answer
Please find the required program along with its output. Please see the comments against each line to understand the step.
def sort(lst):
for i in range(len(lst)): #loop for each element in the list
for j in range(i+1, len(lst)): #loop to check equality against rest of the list from position i+1
if lst[i] > lst[j]: #if the name at position i greater than name at position j
lst[j], lst[i] = lst[i], lst[j] #swap the names in positions i and j
return lst
names = []
print("Enter 5 names ")
for i in range (5): #loop to read 5 names
x=input("Enter name {0} : ".format(i+1)) #read the name
names.append(x) #append the name to the list
sort(names)
print("After sorting:",names) #print the list after sorting
------------------------------------------------
OUTPUT:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.