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?
Checking each two points is not necessary and it's slow O(n^2).
I suggest to:
1) Sort the input.
2) Compare each two following values and choose smallest.
Timing will be much better O(n*log n) assuming that you use efficient sorting algorithm.
Code example:
input = [0, 65, 10, 100, 1231] #whatever you put here; it might be tuple, list, set, range, etc.
def find_closest(input):
sorted_input = sorted(input)
best = (sorted_input[-2], sorted_input[-1], sorted_input[-1] - sorted_input[-2])
for i, val in enumerate(sorted_input[:-1]):
d = sorted_input[i+1]-val
if d < best[2]:
best = (val, sorted_input[i+1], d)
return best
Function returns both values and distance between them.