Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for When "k" is Enough! by kt1729
from typing import Iterable, Any
def remove_after_kth(items: list[Any], k: int) -> Iterable[Any]:
d = {i:0 for i in set(items)}
out = []
for i in items:
if d[i] < k:
out.append(i)
d[i] += 1
return out
# print("Example:")
# print(list(remove_after_kth([42, 42, 42, 42, 42, 42, 42], 3)))
# # These "asserts" are used for self-checking
# assert list(remove_after_kth([42, 42, 42, 42, 42, 42, 42], 3)) == [42, 42, 42]
# assert list(remove_after_kth([42, 42, 42, 99, 99, 17], 0)) == []
# assert list(remove_after_kth([1, 1, 1, 2, 2, 2], 5)) == [1, 1, 1, 2, 2, 2]
# print("The mission is done! Click 'Check Solution' to earn rewards!")
Dec. 30, 2022
Comments: