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

Load Balancing in Bluemix using custom domain and DNS SRV records -

oracle - pls-00402 alias required in select list of cursor to avoid duplicate column names -

python - Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] error -