fork download
  1. import numpy as np
  2. from scipy.spatial.distance import cdist
  3.  
  4. coordinates = [np.array([[300, 2300],
  5. [670, 2360],
  6. [400, 2300]]),
  7. np.array([[1500, 1960],
  8. [1620, 2200],
  9. [1505, 1975]]),
  10. np.array([[980, 1965],
  11. [1060, 2240],
  12. [1100, 2250],
  13. [980, 1975]]),
  14. np.array([[565, 1940],
  15. [680, 2180],
  16. [570, 1945]])]
  17.  
  18.  
  19. lasts = [arr[-1] for arr in coordinates]
  20. firsts = [arr[0] for arr in coordinates]
  21.  
  22. res, coordinates = [coordinates[0]], coordinates[1:]
  23.  
  24. while coordinates:
  25. lasts = res[-1][-1].reshape(1, -1)
  26. distances = cdist(lasts, firsts).flatten()
  27. nearest = np.argmin(distances)
  28. res.append(coordinates.pop(nearest))
  29. firsts.pop(nearest)
  30.  
  31.  
  32. print(res)
  33.  
Success #stdin #stdout 0.28s 44908KB
stdin
Standard input is empty
stdout
[array([[ 300, 2300],
       [ 670, 2360],
       [ 400, 2300]]), array([[1500, 1960],
       [1620, 2200],
       [1505, 1975]]), array([[ 980, 1965],
       [1060, 2240],
       [1100, 2250],
       [ 980, 1975]]), array([[ 565, 1940],
       [ 680, 2180],
       [ 570, 1945]])]