Let's say I have a list: l=[7,2,20,9]
and I wan't to find the minimum absolute difference among all elements within (in this case it would be 9-7 = 2 or equivalently |7-9|). To do it in nlogn complexity, I need to do sort, take the difference, and find the minimum element:
import numpy as np
sorted_l = sorted(l) # sort list
diff_sorted = abs(np.diff(sorted_l)) # get absolute value differences
min_diff = min(diff_sorted) # get min element
However, after doing this, I need to track which elements were used in the original l
list that gave rise to this difference. So for l
the minimum difference is 2 and the output I need is 7 and 9 since 9-7 is 2. Is there a way to do this? sorted
method ruins the order and it's hard to backtrack. Am I missing something obvious? Thanks.
CodePudding user response:
Use:
index = diff_sorted.tolist().index(min_diff)
sorted_l[index:index 2]
Output
[7, 9]
Whole Script
import numpy as np
l=[12,24,36,35,7]
sorted_l = sorted(l)
diff_sorted = np.diff(sorted_l)
min_diff = min(diff_sorted)
index = diff_sorted.tolist().index(min_diff)
sorted_l[index:index 2]
Output
[35, 36]
Explanation
tolist
is transforming the numpy array into a list whose functions contain a index
which gives you the index of the input argument. Therefore, using tolist
and index
functions, we get the index of the minimum in the sorted array. Using this index, we get two numbers which resulted the minimum difference ([index:index 2] is selecting two number in the sorted array)