Advertisement
karlakmkj

Practice - find median

Feb 17th, 2021
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.77 KB | None | 0 0
  1. '''
  2. Write a function that takes a list as an input and returns the median value of the list.
  3.  
  4.    The list can be of any size and the numbers are not guaranteed to be in any particular order. Make sure to sort it!
  5.    If the list contains an even number of elements, your function should return the average of the middle two.
  6.  
  7. '''
  8. def median(list_nums):
  9.   list_nums = sorted(list_nums)
  10.   middle = len(list_nums)/2.0   # Find index of the middle no.
  11.   if len(list_nums) %2 !=0: # If list contains odd no. of elements  
  12.     return list_nums[int(middle-0.5)] # because index starts at 0
  13.   else:
  14.     a = len(list_nums)/2
  15.     b = a - 1
  16.     average = (list_nums[int(a)] + list_nums[int(b)])/2.0
  17.     return average
  18.  
  19. print median([7,3,1,4])
  20. print median([5, 2, 3, 1, 4])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement