Created
February 4, 2023 17:40
-
-
Save aybruhm/d5cadfcb480be210a34deb3ba8da2504 to your computer and use it in GitHub Desktop.
Have the function ArrayChallenge(arr) read the array of numbers stored in arr which will contain a sliding window size, N, as the first element in the array and the rest will be a list of numbers. Your program should return the Moving Median for each element based on the element and its N-1 predecessors, where N is the sliding window size. The f…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def ArrayChallenge(arr): | |
# N -> first number in array | |
N = arr[0] | |
# empty list of numbers | |
res = [] | |
# loop through the length of arrays, | |
# starting from one | |
for i in range(1, len(arr)): | |
# check if number is less than N (first number in array) | |
if i < N: | |
# slice starts from the index 1 to the index i + 1. | |
window = arr[1:i+1] | |
else: | |
# slice starts from the index i - n + 1 to the index i + 1. | |
window = arr[i-N+1:i+1] | |
# sort window to start from the lowest number to the highest | |
window.sort() | |
# calculates the median of a list of numbers | |
if len(window) % 2 == 0: | |
median = ( | |
window[len(window)//2 - 1] + window[len(window)//2] | |
) / 2 | |
else: | |
median = window[len(window)//2] | |
# append calculated median to empty list of numbers | |
res.append(int(median)) | |
# return the array as integers | |
return ",".join(str(x) for x in res) | |
print(ArrayChallenge(input())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment