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?

3
  • for starters, altering the container you're looping on is not recommended: stackoverflow.com/questions/1637807/… Commented Jan 25, 2021 at 8:00
  • I agree with you that this is not a good idea, but I see no other solution than altering between the containers. Commented Jan 25, 2021 at 8: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? Commented Jan 25, 2021 at 8:08

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Will your second loop ever run? I mean, spread_points is an empty list and you try to loop over every element in it.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.