get_subarray_closest_sum

selfeeg.utils.utils.get_subarray_closest_sum(arr: ArrayLike, target: float, tolerance: float = 0.01, perseverance: int = 1000, return_subarray: bool = True) tuple[list, list | None][source]

find the subarray whose values sum is closer to a target.

The solution found is the first inside a specified tolerance (if possible) and return the index of the selected values in the original array.

To find the subarray, get_subarray_closest_sum calls multiple times the subarray_closest_sum function until the subarray has the sum within [target*(1-tolerance), target*(1+tolerance)]. At each try the array is shuffled in order to get a different solution. Keep in mind that the solution is not always the optimal, but rather the first which satisfies the requirements given.

Parameters:
  • arr (ArrayLike) – The array to search.

  • target (float) – The target sum.

  • tolerance (float, optional) –

    The tolerance to apply to the sum in percentage, in range [0,1].

    Default = 0.01

  • perseverance (int, optional) –

    The maximum number of tries before stopping searching the subarray with closest sum.

    Default = 1000

  • return_subarray (bool, optional) –

    whether to also return the subarray or not.

    Default = True

Returns:
  • final_idx (list) – A list with the index of the identified subarray.

  • best_sub_arr (list, optional) – The subarray.

Example

>>> import random
>>> import selfeeg.utils
>>> random.seed(1235)
>>> arr = [i for i in range (1,100)]
>>> final_idx, best_sub_arr = utils.get_subarray_closest_sum(
...     arr, 3251, perseverance=10000)
>>> print( sum(best_sub_arr)) #should print 3251