pythonfor-loopclosest-points

Get the two closest points from a list of points


I am given a list of integers/floats and I need to find the two numbers closest together. How would I do that using only nested for loops?


Solution

  • For each element, you have to compare the distance of it to each of the other elements with your previous "closest" value - any time this comparison yields smaller values, you remember that pair as the "two closest" ones.

    So, it is straightforward:

    def find_two_closest(numbers):
        # most distant points:
        delta = max(numbers), min(numbers)
        for i, element in enumerate(numbers):
            for j, sec_element in enumerate(numbers):
                if i == j:
                    continue
                if abs(sec_element - element) < abs(delta[0] - delta[1]):
                    delta = sec_element, element
        return delta