'Two 2D array's of coordinates, finding if any of the coordinates from the different arrays are within a set distance of one another (python)

I have been trying to figure out how to make it so there is two 2D arrays, each containing a number of arrays that have x and y coordinates for set objects of the same class. The two arrays contain coordinates of objects of two different classes. I've been trying to essentially do a scan of each points surroundings, if there is an object of the other class within a 2 unit radius of the first point it should be spotted and the coordinates added to another array. I was wondering if anyone would be able to help me? I'm quite new to python so this may be pretty easy and I may have missed something obvious.



Solution 1:[1]

Split into two lists:

apples = [x for x in objects if isinstance(x, Apple)]
oranges = [x for x in objects if isinstance(x, Orange)]

Then compare all of them against each other, brute-force, i.e. O(n^2):

colliding_pairs = [
    (a, o)
    for a in apples
    for o in oranges
    if dist(a, o) <= 2
]

where:

def dist(a, b):
    return sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mateen Ulhaq