使用排序查找列表中的两个最接近的数字 [英] Finding the two closest numbers in a list using sorting

查看:280
本文介绍了使用排序查找列表中的两个最接近的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果给我一个整数/浮点数列表,我该如何使用排序找到两个最接近的数字?

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

推荐答案

这种方法可以完成您想要的事情:

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]

在第一个for循环中,我们找出最小距离,在第二个循环中,我们打印具有该距离的所有对.如下所示:

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
>>> 

这篇关于使用排序查找列表中的两个最接近的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆