Search code examples
pythonlistdistancepointsthreshold

Removing points from list if distance between 2 points is below a certain threshold


I have a list of points and I want to keep the points of the list only if the distance between them is greater than a certain threshold. So, starting from the first point, if the the distance between the first point and the second is less than the threshold then I would remove the second point then compute the distance between the first one and the third one. If this distance is less than the threshold, compare the first and fourth point. Else move to the distance between the third and fourth and so on.

So for example, if the threshold is 2 and I have

list = [1, 2, 5, 6, 10]

then I would expect

new_list = [1, 5, 10]

Thank you!


Solution

  • Not a fancy one-liner, but you can just iterate the values in the list and append them to some new list if the current value is greater than the last value in the new list, using [-1]:

    lst = range(10)
    diff = 3
    
    new = []
    for n in lst:
        if not new or abs(n - new[-1]) >= diff:
            new.append(n)
    

    Afterwards, new is [0, 3, 6, 9].


    Concerning your comment "What if i had instead a list of coordinates (x,y)?": In this case you do exactly the same thing, except that instead of just comparing the numbers, you have to find the Euclidean distance between two points. So, assuming lst is a list of (x,y) pairs:

    if not new or ((n[0]-new[-1][0])**2 + (n[1]-new[-1][1])**2)**.5 >= diff:
    

    Alternatively, you can convert your (x,y) pairs into complex numbers. For those, basic operations such as addition, subtraction and absolute value are already defined, so you can just use the above code again.

    lst = [complex(x,y) for x,y in lst]
    
    new = []
    for n in lst:
        if not new or abs(n - new[-1]) >= diff:  # same as in the first version
            new.append(n)
    print(new)
    

    Now, new is a list of complex numbers representing the points: [0j, (3+3j), (6+6j), (9+9j)]