python 2.7 - Finding the two closest numbers in a list using sorting -


if given list of integers/floats, how find 2 closest numbers using sorting?

such method want:

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

in first for loop find out minimum distance, , in second loop, print pairs distance. works 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 >>>  

Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -