Finding the two closest numbers in a list using sorting

前端 未结 3 1044
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-27 09:20

If I am given a list of integers/floats, how would I find the two closest numbers using sorting?

3条回答
  •  孤城傲影
    2021-01-27 09:42

    Such a method will do what you want:

    >>> def minDistance(lst):
        lst = sorted(lst)
        index = -1
        distance = max(lst) - min(lst)
        for i in range(len(lst)-1):
            if lst[i+1] - lst[i] < distance:
                distance = lst[i+1] - lst[i] 
                index = i
        for i in range(len(lst)-1):
            if lst[i+1] - lst[i] == distance:
                print lst[i],lst[i+1]
    

    In the first for loop we find out the minimum distance, and in the second loop, we print all the pairs with this distance. Works as below:

    >>> lst = (1,2,3,6,12,9,1.4,145,12,83,53,12,3.4,2,7.5)
    >>> minDistance(lst)
    2 2
    12 12
    12 12
    >>> 
    

提交回复
热议问题