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?
If the points are one dimensional (as in your input is just a list of numbers like [1, 4, 6, 2]
), then you can easily do it in O(n log n) time by sorting them and finding the ones with the smallest difference:
def smallest_difference(points):
sorted_points = sorted(points)
return min(abs(prev - cur) for cur, prev in zip(sorted_points, sorted_points[1:]))
If you want to get the closest points instead of the distance between the closest points, use the key=
parameter of the min
function:
import operator
def smallest_difference(points):
sorted_points = sorted(points)
return min(zip(sorted_points, sorted_points[1:]), key=lambda x: abs(x[1] - x[0]))
If the points are two dimensional (as in your input is a list of 2 element tuples like [(1, 2), (3, 4), (5, 2)]
) then the Wikipedia article for this problem https://en.wikipedia.org/wiki/Closest_pair_of_points_problem describes how to extend this to two dimensions.