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

Time:12-05

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:

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.

CodePudding user response:

using numpy:

import numpy as np

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

# Compute the cumulative sum of the elements in the array
cumsum = np.cumsum(arr)

# Find the index of the first element in the cumulative sum that is greater than or equal to the target value
index = np.argmax(cumsum >= 40)

# Print the result
print(index)  # Output: 5

CodePudding user response:

To find the index of an array where the summation is greater than a target value in Python, you can use a for loop to iterate over the elements in the array and keep track of the running total. When the running total is greater than the target value, you can return the index at which that occurred.

# define the target value
target = 10

# define the array
arr = [1, 2, 3, 4, 5, 6, 7]

# initialize the running total to 0 and the index to -1
total = 0
index = -1

# iterate over the elements in the array
for i in range(len(arr)):
  total  = arr[i]
  if total > target:
    index = i
    break

# print the index where the summation is greater than the target value
print(index)  # 3

In this example, the index where the summation of the array is greater than the target value is 3. This is because the summation of the first three elements in the array (1 2 3) is greater than the target value of 10.

  • Related