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