0

Given 2 arrays, I want to compare the coordinates of array1 with array2 and print the coordinates if the distance is <= 5. I used the code below, but it is not printing the correct coordinates.

def euclideanDistance(coordinate1, coordinate2):
    dist= pow(pow(coordinate1[0] - coordinate2[0], 2) + pow(coordinate1[1] - coordinate2[1], 2), .5)
    if dist <= 5:
        return (coordinate1, coordinate2)

coords= [[17, 268],[17, 396],[18, 243], [18, 548]]
coords1= [[16, 484],[17, 398],[17, 640],[18, 331]]
distances = []
for i in range(len(coords)-1):
    for j in range(i, len(coords1)):
        distances += [euclideanDistance(coords[i],coords1[j])]
        print(distances)
            

The output should be: [17, 396], [17, 398]

Mary
  • 33
  • 6
  • 2
    Please add expected output and actual output to your question – TheEagle May 16 '21 at 20:14
  • coords= [[ 17 268],[ 17 396],[ 18 243], [ 18 548]] coords1= [[ 16 484],[ 17 398],[ 17 640],[ 18 331]] Output should be [ 17 396], [ 17 398] – Mary May 16 '21 at 20:25

1 Answers1

0

First of all, the function euclideanDistance only returns the coordinates if the distance is larger than 5. Therefore, because you add the result of the function to the array distances, you add a tuple of None, None when the distance is smaller than 5. Therefore, I would return False or any other flag in order to indicate that the dist is not smaller or equal to 5.

Secondly, I don't follow the logic of your for loops - why is the nested for loop only running in the range between i and the length of coords1?

Thirdly, variable names should be meaningful.

Also, you can check out the difference between append() and the + operation on arrays here.

Therefore I would change the code to:

def euclideanDistance(coordinate1, coordinate2):
    dist = pow(pow(coordinate1[0] - coordinate2[0], 2) + pow(coordinate1[1] - 
coordinate2[1], 2), .5)
    if dist <= 5:
        return (coordinate1, coordinate2)
    return False


distances = []
first_cords= [[17, 268],[17, 396],[18, 243], [18, 548]]
second_cords= [[16, 484],[17, 398],[17, 640],[18, 331]]
for f_cord in first_cords:
    for s_cord in second_cords:
        if euclideanDistance(f_cord,s_cord) is not False:
            distances.append([f_cor,s_cord])
print(distances)

Which prints: [[[17, 396], [17, 398]]].

  • please see my edit in question. i need to use the filtered coordinate values further. how can i access new x-coordinate only. how can I print all xcoordinates of new array? – Mary May 17 '21 at 17:46
  • Don't change the question to a different question after your original question has been answered. Please post a new question. –  May 18 '21 at 08:06