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...



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...


items<br>k<br>Expected result<br>[42, 42, 42, 42, 42, 42, 42]<br>3<br>[42, 42, 42]<br>'bob', 'bob',<br>['tom', 42,<br>'bob', 'tom', 'tom', 99]<br>99,<br>2<br>['tom', 42, 'bob',<br>'bob', 99, 'tom', 99]<br>[1, 2, 3, 4, 5, 4, 3, 2, 1, 2,<br>3, 4, 5, 4, 3, 2, 1]<br>1<br>[1, 2, 3, 4, 5]<br>[1, 2, 3, 4, 5, 4, 3, 2, 1, 2,<br>[1, 2, 3, 4, 5, 4, 3,<br>2, 1, 2, 3, 4, 5, 1, 5]<br>3<br>3, 4, 5, 4,<br>3, 2, 1, 2, 3,<br>4, 5]<br>[42, 42, 42, 99, 99, 17]<br>

Extracted text: items k Expected result [42, 42, 42, 42, 42, 42, 42] 3 [42, 42, 42] 'bob', 'bob', ['tom', 42, 'bob', 'tom', 'tom', 99] 99, 2 ['tom', 42, 'bob', 'bob', 99, 'tom', 99] [1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2, 1] 1 [1, 2, 3, 4, 5] [1, 2, 3, 4, 5, 4, 3, 2, 1, 2, [1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 1, 5] 3 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5] [42, 42, 42, 99, 99, 17]

Jun 10, 2022
SOLUTION.PDF

Get Answer To This Question

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here