0

I have a list points of triples containing (x, y, z) where x is the x-coordinate, y is the y-coordinate and z is a magnitude. Now I want to check if any point in the list is within a certain radius to the other points in the list. If so the point in the radius has to be deleted. Therefore I made the following code.

radius = 20
for _, current_point in enumerate(points):
    # get the x and y coordinate of the current point
    current_x, current_y = current_point[0], current_point[1]
    for _, elem in enumerate(points):
        # check if the second point is within the radius of the first point
        if (elem[0] - current_x)**2 + (elem[1] - current_y)**2 < radius**2:
            # remove the point if its within the radius
            points.remove(elem)

When I run this the list still contains points which are within the radius of another point. Is there some property of enumerate that I'm missing here?

jri
  • 402
  • 1
  • 6
  • 15
  • for starters, altering the container you're looping on is not recommended: https://stackoverflow.com/questions/1637807/modifying-list-while-iterating?noredirect=1&lq=1 – Krishna Chaurasia Jan 25 '21 at 08:00
  • I agree with you that this is not a good idea, but I see no other solution than altering between the containers. – jri Jan 25 '21 at 08:07
  • could you not create another list based on the satisfying criteria and overwrite the original list with the new list after the processing is complete? – Krishna Chaurasia Jan 25 '21 at 08:08

1 Answers1

1

You can iteratively build a new list containing points satisfying the condition.

radius = 20
spread_points = []
for point in points:
    # get the x and y coordinate of the current point
    current_x, current_y = point[0], point[1]
    for sp in spread_points:
        # check if the second point is within the radius of the first point
        if (sp[0] - current_x)**2 + (sp[1] - current_y)**2 < radius**2:
            break
    else:
        spread_points.append(point)

For a more efficient algorithm, perhaps you can use https://en.wikipedia.org/wiki/Quadtree.

Or to just speed this up, you can use numpy arrays to speed up the one point to many points distance computation.

Alex
  • 947
  • 6
  • 16
  • Will your second loop ever run? I mean, spread_points is an empty list and you try to loop over every element in it. – jri Jan 25 '21 at 08:17
  • 1
    Yes, when `spread_points` is empty, the for loop else will run (since the loop was not `break`'ed out of) and then `spread_points` will no longer be empty. – Alex Jan 25 '21 at 08:19