
Dec. 26, 2021
10:07 p.m.
Steven D'Aprano wrote:
Can you sketch an O(n) algorithm for removing multiple items from an array, which *doesn't* involving building a temporary new list?
Here's what I meant. Have read/write indexes, delete the gap after maxcount occurrences: def remove(lst, value, maxcount): read = write = 0 while maxcount > 0 and read < len(lst): if lst[read] == value: maxcount -= 1 else: lst[write] = lst[read] write += 1 read += 1 del lst[write:read] Note that the remaining elements aren't looked at, just their references are memmoved (or whatever del does).