I got requested result with below codes, another approach than what Marcos provided and I was able to find as well. Only additional thing is you need is to pad arrays to maximum length + 1
with numpy pad
.
def elementsum2array(arr1, arr2):
'''
1. Make the arrays of same length padding at the beginning/left side with 0's
so that arrays get the same same length of "maximum length + 1" (for carry at the end).
2. Get a new array of length "maximum length + 1".
3. Sum the elements of the arrays from last index to first index together with carry.
4. Fill the new array element with sum % 10.
5. Update carry (sum // 10).
'''
if len(arr1) == 0 and len(arr2) > 0:
return arr2
if len(arr1) > 0 and len(arr2) == 0:
return arr1
if len(arr1) == 0 and len(arr2) == 0:
return []
else:
import numpy as np
maxlen = max(len(arr1), len(arr2))
arr1dif = maxlen - len(arr1) + 1
arr2dif = maxlen - len(arr2) + 1
arr1resized = np.pad(arr1, (arr1dif, 0), 'constant')
arr2resized = np.pad(arr2, (arr2dif, 0), 'constant')
L = len(arr1resized)
arrnew = [0 for num in range(maxlen+1)]
carry = 0
elementsum = 0
for i in range(L-1, -1, -1):
elementsum = (arr1resized[i] + arr2resized[i] + carry)
arrnew[i] = elementsum % 10
#print(arrnew[i])
carry = elementsum // 10
#print(carry)
i=i-1
return arrnew
Example:
arr1 = [3,2,1,0,4,9]
arr2 = [5,1,6,4]
elementsum2array(arr1, arr2)
[0, 3, 2, 6, 2, 1, 3]
This was also done in Java here:
sum of two arrays element wise?
solved Return summation of two lists as elements in a new list