sum of two arrays of different length

Question:

For example I have 2 arrays

arraya[1,1,1,1,1,1,1]
arrayb[0,1,2]

I want to add arrayb to arraya continiously like this:

arraysum[1,2,3,1,2,3,1]

How can I do it?

Asked By: Nhmanas

||

Answers:

arraya = [1,1,1,1,1,1,1]
arrayb = [0,1,2]

for i in range(len(arraya)):
    arraya[i] += arrayb[i % len(arrayb)]

print arraya

Produces
[1, 2, 3, 1, 2, 3, 1]

Answered By: lch

You can use zip combined with cycle for this:

if arrayb:
    arraysum = [sum(x) for x in zip(cycle(arrayb), arraya)]
else:
    arraysum = arraya
Answered By: Nico Griffioen
arraya = [1,1,1,1,1,1,1]
arrayb = [0,1,2]
arraysum = []

i=0

while i in range(len(arraya)):
  arraysum.append(arraya[i] + arrayb[i % len(arrayb)])
  i+=1

print (arraysum)
Answered By: Sanket Patel

I hope this is understandable.

from itertools import cycle

def sum_arr(smaller_array, larger_array):
    new_a = []

    for _ in zip(cycle(smaller_array), larger_array): # cycle(0, 1, 2) => 0 1 2 0 1 2 . . .

        new_a.append(sum(_))

    return new_a

a = [1,1,1,1,1,1,1]
b = [0,1,2]

if len(a) < len(b):  # check which one is the smaller and to be repeated
    new_array = sum_arr(a, b)
else:
    new_array = sum_arr(b, a)

print(new_array) # [1, 2, 3, 1, 2, 3, 1]
Answered By: P.hunter
def Sum():
arrayb = [0,1,2]
arraya = [1,1,1,1,1,1,1]
arraySum = []

counter = 0

for i in range(len(arraya)):
    if i % len(arrayb) == 0:
        counter = 0
    
    arraySum.append(arraya[i] + arrayb[counter])
    counter+=1
return arraySum
Answered By: Ali Shahen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.