PythonSOS PythonSOS - 2 years ago 114
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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download