I would like to make the following sum given two lists:
a = [0,1,2,3,4,5,6,7,8,9]
b = [2,3,5]
The result should be the sum of the every b
element of a
like:
b[0] = 2
so the first sum result should be: sum(a[0:2])
b[1] = 3
so the second sum result should be: sum(a[2:5])
b[2] = 5
so the third sum result should be: sum(a[5:10])
The printed result: 1,9,35
Using a for loop and range () method, iterate from 0 to the length of the list with the size of chunk as the step. Return the chunks using yield. list_a [i:i+chunk_size] gives each chunk. For example, when i = 0, the items included in the chunk are i to i + chunk_size which is 0 to (0 + 2)th index.
We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return the largest number of chunks we can make to sort the array. Input: arr = [4,3,2,1,0] Output: 1 Explanation: Splitting into two or more chunks will not return the required result.
Input: arr = [1,0,2,3,4] Output: 4 Explanation: We can split into two chunks, such as [1, 0], [2, 3, 4]. However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.
In the while loop, we will access each element in the list using the count variable and add them to sumOfElements. After that, we will increment the value of the count by 1. We will continue this process until the count becomes equal to the length of the list. You can write a program to find the sum of elements in a list in python as follows.
You can make use of np.bincount
with weights
:
groups = np.repeat(np.arange(len(b)), b)
np.bincount(groups, weights=a)
Output:
array([ 1., 9., 35.])
NumPy has a tool to do slice based sum-reduction with np.add.reduceat
-
In [46]: np.add.reduceat(a,np.cumsum(np.r_[0,b[:-1]]))
Out[46]: array([ 1, 9, 35])
Hard to compete with the np.bincount
solution, but here's another nice way to approach it with np.cumsum
:
strides = [0] + np.cumsum(b).tolist() # [0, 2, 5, 10]
stride_slices = zip(strides[:-1], strides[1:]) # [(0, 2), (2, 5), (5, 10)]
[sum(a[s[0]: s[1]]) for s in stride_slices]
# [1, 9, 35]
You mean something like this?
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [2, 3, 5]
def some_function(a, b): # couldnt come up with a name :D
last_index = 0
for i in b:
print(sum(a[last_index:last_index + i]))
last_index += i
some_function(a, b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With