I need to run through a list, and remove all elements that don't satisfy certain conditions. Specifically, every time I have two consecutive elements A and B where A is negative and B is positive (all elements are non-zero), and the ratio of these elements is less than some given ratio, they should be removed. All other elements should remain.
At first, I was looping through the list, and removing directly. However, since I was looping through the length of the list, and the loop was actually changing this length, I was having index errors. So I figured I would just make a new list with all the elements that DO satisfy the conditions, instead of removing. Is this the right approach? Here is my code:
d_list = [1, -6, 7, -10, 11, -12, 13, -15, 17, -18, 19, -20, 23, -24, 29, -30, 31]
J = []
for i in range(0, len(d_list) - 1):
if ((d_list[i] < 0) & (d_list[i+1] > 0)):
if(math.fabs(d_list[i+1] / d_list[i]) >= 6/5):
J.append(d_list[i])
J.append(d_list[i+1])
else:
J.append(d_list[i])
I should have as output: [1, -24, 29]
.
However I get: [1, 7, 11, 13, 17, 19, 23, -24, 29, 29]
.
I am super confused, and have tried several variations of the code I have showed above, without success.
Here you go:
import math
d_list = [1, -6, 7, -10, 11, -12, 13, -15, 17, -18, 19, -20, 23, -24, 29, -30, 31]
J = []
skip = []
for i in range(0, len(d_list) - 1):
if i in skip:
continue
if d_list[i] < 0 < d_list[i+1]:
if math.fabs(d_list[i+1] / d_list[i]) >= 6/5:
J.append(d_list[i])
else:
skip.append(i+1)
else:
print(d_list[i])
J.append(d_list[i])
print(J)
Output:[1, -24,-29]
The problem is you are appending both elements instead of one, and if element is invalid you should skip it in the next check because it already failed the condition. For example we have
A->B->C
If A->B fail you should remove them both, and your code omits A and then checks if B->C are valid they are so you add them both and you shouldn't.
I am hoping this is clear if you'd like I can elaborate more.
Edit: You could also do it without skipping list just with bool value like so:
import math
d_list = [1, -6, 7, -10, 11, -12, 13, -15, 17, -18, 19, -20, 23, -24, 29, -30, 31]
J = []
skip = False
for i in range(0, len(d_list) - 1):
if skip:
skip = False
continue
if d_list[i] < 0 < d_list[i+1]:
if math.fabs(d_list[i+1] / d_list[i]) >= 6/5:
J.append(d_list[i])
else:
skip =True
else:
print(d_list[i])
J.append(d_list[i])
print(J)
Output:[1, -24,-29]
However, the first approach retains information why the element was removed.