iamtesla
iamtesla

Reputation: 423

python creating convolve function for arrays

I have two arrays,

a = [3, 6, 8, 2, 5, 5]
b = [2, 7, 9]

and I need to create a new array c which takes the values and adds them like this: a[0+0]*b[0] + a[0+1]*b[1] + a[0+2]*b[2] = (3*2) + (6*7) + (9*8) = 6 + 42 + 72 which means c[0] = 120

I'm completely lost on how to do this anything to point me in the right direction would be awesome.

Upvotes: 3

Views: 202

Answers (4)

Jeff
Jeff

Reputation: 7210

numpy.convolve or do you want to write your own function?

Upvotes: 0

Blckknght
Blckknght

Reputation: 104712

I think this will do what you want. It borrows some of the code from @DukeSilver's answer and makes it build a list, rather than just calculating a single value. My assumption is that a is always longer than b.

c = [sum(a[i+j]*b[j] for j in range(len(b))) for i in range(len(a) - len(b) + 1)]

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304175

If c[k] = a[k+0]*b[0] + a[k+1]*b[1] + a[k+2]*b[2]

then

>>> c = [sum(i*j for i,j in zip(a[k:], b)) for k in range(4)]
>>> c
[120, 86, 75, 84]

Upvotes: 1

Duke Silver
Duke Silver

Reputation: 1629

total = 0
for n in range(0, min(len(a), len(b))):
    total += a[n] * b[n]

range function

Upvotes: 1

Related Questions