Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find the index of an array where summation is greater than a target value?

Suppose I have a 1D array sorted in descending order, like:

arr = np.array([10, 10, 8, 5, 4, 4, 3, 2, 2, 2])

I want the index value, where the summation of this array starting from 0 to that index is greater than or equal to a specified target value. For example, let the target value be 40:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

index=0 (0) => sum=10 (10)

index=1 (0,1) => sum=20 (10+10)

index=2 (0,1,2) => sum=28 (10+10+8)

index=3 (0,1,2,3) => sum=33 (10+10+8+5)

index=4 (0,1,2,3,4) => sum=37 (10+10+8+5+4)

index=5 (0,1,2,3,4,5) => sum=41 (10+10+8+5+4+4)

and finally I want to get the index value 5, since the sum 41 is greater than the target value 40. How can I do this in most Pythonic and appropriate way, so it can work with large numbers and large sized arrays.

>Solution :

If you can leverage the standard libs – itertools accumulate, then you can try this approach:

Lastly, is to use bisect module to find the right index for your target value.

from itertools import accumulate

L = [10, 10, 8, 5, 4, 4, 3, 2, 2, 2]
# idx    1   2     4  5   6  7  8  9

# making a mapping from the accumulated sums:
accu = list(accumulate(L))
print(accu)
#[10, 20, 28, 33, 37, 41, 44, 46, 48, 50]

mapping = {n: idx for idx, n in enumerate(accu) }
print(mapping)
{10: 0, 20: 1, 28: 2, 33: 3, 37: 4, 41: 5, 44: 6, 46: 7, 48: 8, 50: 9}

# then finally last step is to use bisect module to find the index:
# leave for your last exercise.  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading