def closest(v, L):
    """
    Returns the element in L (a sorted numpy array) which is closest to v

    >>> R = np.array([9,3,6])
    >>> R.sort()
    >>> R
    array([3, 6, 9])
    >>> [closest(i, R) for i in range(1,12)]
    [3, 3, 3, 3, 6, 6, 6, 9, 9, 9, 9]
    """
    i = L.searchsorted(v)
    return L[-1 if i == len(L) else (0 if i == 0 else (i if v - L[i - 1] > L[i] - v else i - 1))]