wish of those help Well, you cannot do this faster than O(N) because you have to check all numbers to be sure you have the closest one. That said, why not use a simple variation on finding the minimum, looking for the one with the minimum absolute difference with x? If you can say the list is ordered from the beginning (and it allows random-access, like an array), then a better approach is to use a binary search. When you end the search at index i (without finding x), just pick the best out of that element and its neighbors.
How do I find the closest n numbers to a given number at x distance from it?
should help you out How would you find the closest number in comparison to numbers given in a list? This is what I have tried but I have come of unsuccessfull: , If you are too new to understand lambda functions yet,
minimum = float("inf")
setted_list = [2,9,6,20,15]
value_chosen = 17
for val in setted_list:
if abs(val - value_chosen) < minimum:
final_value = val
minimum = abs(val - value_chosen)
Find three Numbers with Sum closest to a given number
like below fixes the issue As we worked out in the comments the last return statment was erroneously inside the for loop cutting it short after the first iteration. Also, closest should be updated in both branches where we overshoot or undershoot the target. I think an obvious improvement of your algorithm would be to sort first. Removing individual elements doesn't destroy order, so you'd need to sort only once. That would get you from O(n^2 log n) to O(n^2).
Find combination of numbers such that their addition is closest to a number?