PythonSOS PythonSOS - 1 year ago 87
Python Question

Two closest points in list?

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?

Answer Source

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:
            if abs(sec_element - element) < abs(delta[0] - delta[1]):
                delta = sec_element, element
    return delta