Try with formulas instead of list.
Try with list instead of functions.
Adjust the inner loop to minimal distance.
Try with functions again.
Include itertools.
Adjust everything to functional style (itertools).