If I have a number and a list of numbers, is there a fast way to find the closest value in the list to the input number? For example, if I have the number 5 and the list [1, 7, 10, 15], I’d like to be able to quickly pull 7 from the list.
python’s min can do this, but I can’t seem to implement the same functionality with hl.min(). Is there a workaround, or am I missing something?
hl.binary_search would return the index of the closest larger number in a sorted list. In the example, it works for input 5 (returns 7). But it doesn’t work for input 2 (also returns 7).
Another option would be to sort the list using a key and take the first element.
hl.sorted(ls, lambda n: hl.abs(n - input))[0]
@danking’s find_nearest function would be more efficient than sorting though.