Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- This problem was asked by Microsoft.
- Compute the running median of a sequence of numbers. That is, given a stream of numbers, print out the median of the list so far on each new element.
- Recall that the median of an even-numbered list is the average of the two middle numbers.
- For example, given the sequence [2, 1, 5, 7, 2, 0, 5], your algorithm should print out:
- 2
- 1.5
- 2
- 3.5
- 2
- 2
- 2
- '''
- def median(sublist):
- n = len(sublist)
- sublist = sorted(sublist)
- if n % 2 == 0:
- return 0.5 * (sublist[int(n/2)-1] + sublist[int(n/2)])
- else:
- return sublist[int((n-1)/2)]
- def medians(myList):
- result = list()
- result.append(myList[0])
- for i in range(1, len(myList)):
- sublist = myList[0:i+1]
- result.append(median(sublist))
- return result
- # MAIN FUNCTION
- print(medians([2, 1, 5, 7, 2, 0, 5]))
- print(medians([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement