Home > Mobile >  Efficiently adding two different sized one dimensional arrays
Efficiently adding two different sized one dimensional arrays

Time:11-09

I want to add two numpy arrays of different sizes starting at a specific index. As I need to do this couple of thousand times with large arrays, this needs to be efficient, and I am not sure how to do this efficiently without iterating through each cell.

a = [5,10,15]
b = [0,0,10,10,10,0,0]

res = add_arrays(b,a,2)

print(res) => [0,0,15,20,25,0,0]

naive approach:

# b is the bigger array 
def add_arrays(b, a, i):
    for j in range(len(a)):
        b[i j] = a[j] 

CodePudding user response:

You might assign smaller one into zeros array then add, I would do it following way

import numpy as np
a = np.array([5,10,15])
b = np.array([0,0,10,10,10,0,0])
z = np.zeros(b.shape,dtype=int)
z[2:2 len(a)] = a  # 2 is offset
res = z b
print(res)

output

[ 0  0 15 20 25  0  0]

Disclaimer: I assume that offset len(a) is always less or equal len(b).

CodePudding user response:

Nothing wrong with your approach. You cannot get better asymptotic time or space complexity. If you want to reduce code lines (which is not an end in itself), you could use slice assignment and some other utils:

def add_arrays(b, a, i):
    b[i:i len(a)] = map(sum, zip(b[i:i len(a)], a))

But the functional overhead should makes this less performant, if anything.

Some docs:

  • Related