In: Computer Science
Beginning Python Programming - Sorting: Write and test a Python program to print a set of real numbers in descending order. The program should also print out the median of the numbers input and how many numbers were input. The program should read in numbers until a negative number is read. The negative number serves as a sentinel or marker telling the program when to stop reading numbers. The program should then sort the numbers and print them out in order from largest to smallest. Note, the sentinel number is not to be considered as one of the numbers, it should not be printed. The program should be able to handle up to 100 input numbers. If the user attempts to enter more than 100 numbers, the program should print an error message and quit.
def sortdesc(list):
Number=len(list)
for i in range (Number):
for j in range(i + 1, Number):
if(list[i] < list[j]):
temp = list[i]
list[i] = list[j]
list[j] = temp
return list
def median(lst):
sortedLst = sortdesc(lst)
lstLen = len(lst)
index = (lstLen - 1) // 2
if (lstLen % 2):
return sortedLst[index]
else:
return (sortedLst[index] + sortedLst[index + 1])/2.0
list=[]
cnt=1
while(True):
#check for more than 100 times
if(cnt>100):
print("Input more than 100 not allowed!")
exit();
n=int(input("Enter numbers (-ve number to stop ): "))
if(n<0):
break
else:
list.append(n)
cnt=cnt+1
#call sort method
sort_list=sortdesc(list)
print("Sorted lis is: ")
for i in range(len(sort_list)):
print(sort_list[i],end=' ')
#print median
print("\nMedian is: ",median(list))