fork(2) download
  1. #Create a function that returns the median of a list of numbers
  2. def median(list_of_numbers):
  3.  
  4. #Make a copy of list_of_numbers and sort the new list
  5. lst = list_of_numbers
  6. lst = sorted(lst)
  7.  
  8. #Get the length of list and use it to index through the list
  9. lst_length = len(lst)
  10. index = int(lst_length/2)
  11.  
  12. #If length if even, average the two middle numbers
  13. if lst_length%2==0:
  14. a= lst[index-1]
  15. b = lst[index]
  16. result = (a+b)/2
  17.  
  18. #If length is odd, return the middle number
  19. else:
  20. result = lst[index]
  21. return result
  22.  
  23. print (median([4, 5, 5, 4]))
Success #stdin #stdout 0.01s 7852KB
stdin
Standard input is empty
stdout
4