Get the two closest points from a list of points

后端 未结 3 1588
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-29 07:14

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?

3条回答
  •  执念已碎
    2021-01-29 08:07

    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
    

提交回复
热议问题