def remove_after_kth(items, k=1): Given a list of items, some of which may be duplicated, create and return a new list that is otherwise the same as items, but only up to k occurrences of each element are kept, and all occurrences of that element after those first k are discarded. Hint: loop through the items, maintaining a dictionary that remembers how many times you have already seen each element. Update this count as you go, and append each element to the result list only if its count is still at most equal to k. Note the counterintuitive and yet completely legitimate edge case of k==0 that has the well defined and unambiguously correct answer of an empty list! Once again, an often missed and yet so very important part of becoming a programmer is learning to perceive zero as a number.
That's enough of you!
def remove_after_kth(items, k=1):
Given a list of items, some of which may be duplicated, create and return a new list that is otherwise the same as items, but only up to k occurrences of each element are kept, and all occurrences of that element after those first k are discarded.
Hint: loop through the items, maintaining a dictionary that remembers how many times you have already seen each element. Update this count as you go, and append each element to the result list only if its count is still at most equal to k.
Note the counterintuitive and yet completely legitimate edge case of k==0 that has the well defined and unambiguously correct answer of an empty list! Once again, an often missed and yet so very important part of becoming a programmer is learning to perceive zero as a number...
Step by step
Solved in 2 steps