Created
May 6, 2025 07:32
-
-
Save j-faria/0747b4dd2e35a6a502d380882518ffc6 to your computer and use it in GitHub Desktop.
Linearly and maximally spaced values from an array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def linspaced_in_range(arr, n, return_indices=False, return_reverse_indices=False): | |
""" Return n values spaced linearly from within arr """ | |
i = np.linspace(0, arr.size - 1, n, dtype=int) | |
spaced = np.sort(arr)[i] | |
spaced_i = np.argsort(arr)[i] | |
spaced_ri = np.array(list(set(np.arange(arr.size)) - set(spaced_i))) | |
ret = [spaced] | |
if return_indices: | |
ret.append(spaced_i) | |
if return_reverse_indices: | |
ret.append(spaced_ri) | |
if len(ret) == 1: | |
ret = ret[0] | |
return ret | |
def maxspaced_in_range(arr, n, return_indices=False, return_reverse_indices=False): | |
""" Return n values maximally spaced from within arr """ | |
if n > arr.size: | |
raise ValueError(f"arr has size {arr.size}, but trying to get {n} values") | |
step1 = step2 = n // 2 | |
step1 += 1 if (n % 2 != 0) else 0 # for odd n, take one extra value from the "bottom" | |
sorted = np.sort(arr) | |
spaced = np.r_[sorted[:step1], sorted[-step2:]] | |
arg_sorted = np.argsort(arr) | |
spaced_i = np.r_[arg_sorted[:step1], arg_sorted[-step2:]] | |
spaced_ri = np.array(list(set(np.arange(arr.size)) - set(spaced_i))) | |
ret = [spaced] | |
if return_indices: | |
ret.append(spaced_i) | |
if return_reverse_indices: | |
ret.append(spaced_ri) | |
if len(ret) == 1: | |
ret = ret[0] | |
return spaced |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment