Home > Software design >  Iteration over elements of 1D array is giving index error after few iterations
Iteration over elements of 1D array is giving index error after few iterations

Time:05-16

I have an array 'A' consisting of 15 elements. I have to delete a few elements and make the array with 8 elements. I have to compare the adjacent elements and for the minimum value of the difference between them, it should delete the second element and so on. The iteration should continue till the number of elements becomes 8. I am getting the error: IndexError: index 13 is out of bounds for axis 0 with size 13. Here is my code:

A = [1, 11, 21, 105, 115, 134, 139, 149, 152, 180, 190, 195, 200, 210, 236]
k = 0
while len(A) > 8:
    for i in range(len(A) - 1):
        x = A[i-1]
        y = A[i]
        if abs(x-y) == k:
            A = np.delete(A, np.argwhere(A == y))
    if len(A) == 8:
        print("Final A= ", A)
    k = k 1

CodePudding user response:

Your error seems to be in the line:

A = np.delete(A, np.argwhere(A == y))

The code will continue to loop after this condition is met, potentially resulting in multiple removals in one iteration of the for loop. To solve this, simply add a break after this line, to break the loop and reevaluate the array's size:

if abs(x-y) == k:
      A = np.delete(A, np.argwhere(A == y))
      break

CodePudding user response:

You could use a single loop iterating len(A)-8 times to remove a single element per iteration. Subtract the array from a shifted version to calculate differences between successive elements and remove the right element with the minimum difference. Finally print outside the loop.

import numpy as np 

A = np.array([1, 11, 21, 105, 115, 134, 139, 149, 152, 180, 190, 195, 200, 210, 236])

for k in range(len(A)-8):
    diff = np.abs(A[1:] - A[:-1]) 
    A = np.delete(A, np.argmin(diff) 1)

print("Final A = ", A)

Gives:

Final A = [ 1 21 105 134 149 180 200 236]
  • Related