PythonSOS - 1 year ago 109

Python Question

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?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

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:
continue
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**