Cody Bable

Generation

generate functionTue, 23 May 2023

given a set of integers and a value for which you need to find the nearest one.

def find_closest(A, target): A.sort() min_diff = float("inf") low = 0 high = len(A) - 1 closest_num = None if len(A) == 0: return None if len(A) == 1: return A[0] while low <= high: mid = (low + high) // 2 if mid + 1 < len(A): min_diff_right = abs(A[mid + 1] - target) if mid > 0: min_diff_left = abs(A[mid - 1] - target) # check if the absolute value between left and right elements are smaller than any seen prior if min_diff_left < min_diff: min_diff = min_diff_left closest_num = A[mid - 1] if min_diff_right < min_diff: min_diff = min_diff_right closest_num = A[

Questions about programming?Chat with your personal AI assistant