Skip to content

Instantly share code, notes, and snippets.

@jackersson
Created March 30, 2021 16:30
Show Gist options
  • Save jackersson/6cadffef1f140ea5c2f1d7147d8e38a9 to your computer and use it in GitHub Desktop.
Save jackersson/6cadffef1f140ea5c2f1d7147d8e38a9 to your computer and use it in GitHub Desktop.
Coding Assignment
def moving_median(arr):
numbers = arr[1:]
sliding_window_size = min(len(numbers), arr[0])
i = 1
result = []
while i < (len(numbers) + 1):
index_from = max(0, (i - sliding_window_size))
window_numbers = numbers[index_from:i]
# we need to change window size when number of elements less than window size
current_window = min(len(window_numbers), sliding_window_size)
# from median definition:
# [2, 3, 4] -> 3 (middle element)
# [2, 4] -> (2 + 4) / 2 (average)
if current_window % 2 != 0:
window_median = sorted(window_numbers)[int((current_window - .5) / 2)]
else:
window_median = sum(window_numbers) // 2
result.append(window_median)
i += 1
return result
assert moving_median([5, 2, 4, 6]) == [2, 3, 4]
assert moving_median([3, 0, 0, -2, 0, 2, 0, -2]) == [0] * 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment