Remove values from an array in-place
Two easy and neat little algorithms to remove values (say ‘x’) from an array in-place (without allocating space for a new array).
The first idea is that I don’t need to sheft any element before the first ‘x’; I need to shift elements between the first ‘x’ and the second ‘x’ one place to the left, and so on.
def remove_element(value,array): shift = 0 for index in xrange(len(array)): try: array[index] = array[index + shift] while array[index] == value: shift += 1 array[index] = array[index + shift] except IndexError: array[index] = None
The second idea is to have two indeces, one for reading and one for writing, both starting at the begin of the array. I move them both forward for characters different than ‘x’; when char is ‘x’, only the reading index is moved forward.
def remove_element(value, array): reading_idx = writing_idx = 0 while reading_idx < len(array): if array[reading_idx] != value: array[writing_idx] = array[reading_idx] writing_idx += 1 reading_idx += 1 while writing_idx < len(array): array[writing_idx] = None writing_idx += 1