Home > Net >  Starting with the 1st (ith) element in an array, how can I remove the i 1 element if it is greater t
Starting with the 1st (ith) element in an array, how can I remove the i 1 element if it is greater t

Time:10-03

I have an array, for example A = [110, 109, 108, 115, 107, 115, 106, 105, 115, 115, 105]. Starting at A[0] I want to keep the next element A[i 1] if A[i]-6 < A[i 1] < A[i] 6. So in my example all of the 115's should be removed. When I try using for or while loops, I get index out of range. I assume because A[i 1] doesn't exist. Is there a clever way to do this?

g = 6; Au = []; 
while i < len(A):
    if (A[i 1]-g < A[i] < A[i 1] g):
        Au.append(A[i]) 
    else:
          pass
    i =1

CodePudding user response:

Simplest:

b = [a[0]]

for x, y in zip(a, a[1:]):
    if abs(x - y) < max_diff:
        b.append(y)

CodePudding user response:

Here's a list comprehension that does what you're asking:

A = [110, 109, 108, 115, 107, 115, 106, 105, 115, 115, 105]
g = 6
Au = [
         A[i] 
         for i in range(len(A) - 1) 
         if (A[i 1] - g) < A[i] < (A[i   1]   g)
     ]

But this is roughly the same as your current code, compressed into a single line - except that it goes to len(A) - 1 (thus avoiding an index out of bounds error), not to len(A). Adding this - 1 to your while loop should make your code work properly:

while i < len(A) - 1:
    if (A[i 1]-g < A[i] < A[i 1] g):
        Au.append(A[i]) 
    else:
          pass
    i =1

CodePudding user response:

You can zip A with a shifted version of itself and iterate over those pairs to avoid excessive indexing:

A = [110, 109, 108, 115, 107, 115, 106, 105, 115, 115, 105]
g = 6

Au = [A[0]]   [b for (a, b) in zip(A, A[1:]) if a - g < b < a   g] 
print(Au)
[110, 109, 108, 105, 115]
  • Related