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).
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/DQMTVZMJ2RYG624FALIA7WGBFORMNY6T/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to