JavaScript
x
11
11
1
w = [1, 2, 3, -3, -2, 4, -4, 1, 2, -2]
2
3
4
def data_remover(xarray, ind):
5
for i in ind:
6
del xarray[i]
7
return xarray
8
9
10
print(data_remover(w, [2, 3, 5, 6, 8, 9]))
11
I am trying to write a code such that it removes adjacent (+n, -n) pairs such as (3,-3) (4,-4) etc.
However I cannot use del[i]
since when I remove an element the xarray also changes. I tried to use deepcopy
to copy the x array but I couldnt manage to run the code.
JavaScript
1
14
14
1
from copy import deepcopy
2
3
w = [1, 2, 3, -3, -2, 4, -4, 1, 2, -2]
4
5
6
def data_remover(xarray, ind):
7
xcopy = deepcopy(xarray)
8
for i in ind:
9
del xarray[i]
10
return xarray
11
12
13
print(data_remover(w, [2, 3]))
14
Advertisement
Answer
You can sort the list of indices in descending order so that deleting an element will not effect the position of another. You can do this by reversed(ind)
JavaScript
1
7
1
w = [1, 2, 3, -3, -2, 4, -4, 1, 2, -2]
2
def data_remover(xarray, ind):
3
for i in reversed(ind):
4
del xarray[i]
5
return xarray
6
print(data_remover(w, [2, 3, 5, 6, 8, 9]))
7
Or if your indices are not in any order you can always sort them in descending order.
JavaScript
1
2
1
for i in sorted(ind, reverse = True):
2