Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Explained - Using list as "fifo" solution in Clear category for Median of Three by Selindian
from typing import Iterable
def median_three(els: Iterable[int]) -> Iterable[int]:
# your code here
fifo_of_three = list() # We need a new list
for elem in els: # Lopp over all elements
if len(fifo_of_three) == 3: fifo_of_three.pop(0) # If our fifo reach 3 elements pop the oldest (0).
fifo_of_three.append(elem) # Append next element to fifo
if len(fifo_of_three) < 3: # If we have not reached 3 elements ...
yield fifo_of_three[-1] # ... yield last element as median
else: # Else ...
yield sorted(fifo_of_three)[1] # ... yield the middle element of the sorted fifo as median
if __name__ == '__main__':
print("Example:")
print(list(median_three([1, 2, 3, 4, 5, 6, 7])))
# These "asserts" are used for self-checking and not for an auto-testing
assert list(median_three([1, 2, 3, 4, 5, 6, 7])) == [1, 2, 2, 3, 4, 5, 6]
assert list(median_three([1])) == [1]
print("Coding complete? Click 'Check' to earn cool rewards!")
March 9, 2022
Comments: