python-3.xarray-sum

Sum of Two Arrays - Python


Two random integer arrays/lists have been given as ARR1 and ARR2 of size N and M respectively. Both the arrays/lists contain numbers from 0 to 9(i.e. single digit integer is present at every index). The idea here is to represent each array/list as an integer in itself of digits N and M. You need to find the sum of both the input arrays/list treating them as two integers and put the result in another array/list i.e. output array/list will also contain only single digit at every index.

NOTE: The sizes N and M can be different.

Output array/list(of all 0s) has been provided as a function argument. Its size will always be one more than the size of the bigger array/list. Place 0 at the 0th index if there is no carry.

No need to print the elements of the output array/list.

def sumOfTwoArrays(arr1, n, arr2, m, output) :
    #Your code goes here






#Taking Input Using Fast I/O
def takeInput() :
    n = int(stdin.readline().rstrip())
    if n == 0 :
        return list(), 0
    
    arr = list(map(int, stdin.readline().rstrip().split(" ")))
    return arr, n


#to print the array/list
def printList(arr, n) :
    for i in range(n) :
        print(arr[i], end = " ")
    
    print()


#main
t = int(stdin.readline().rstrip())

while t > 0 :
    arr1, n = takeInput()
    arr2, m = takeInput()
    
    outputSize = (1 + max(n, m))
    output = outputSize * [0]
    
    sumOfTwoArrays(arr1, n, arr2, m, output)
    printList(output, outputSize)
    
    t -= 1

Sample Input: 1

3

6 2 4

3

7 5 6

Sample Output: 1 3 8 0


Solution

  • This problem can be solved by a simple function like this: (Note - you can made adjustment on the last line of return result if needed to meet the "strange requirement" of - 'place 0 at the 0th index if there is no carry'. It's left as a trivial exercise. )

    def sum_two_array(L1, L2):
        carry, total = 0, 0
        m, n = len(L1), len(L2)
        k   = max(m, n)
        
        result = [0] + [0] * k  # add +1 
    
        for i in range(1, k+1):
            a = L1[m-i] if m - i >= 0 else 0
            b = L2[n-i] if n - i >= 0 else 0
         
            total = a + b + carry
            result[k-i + 1] = total % 10
            carry = total // 10
        
        if carry > 0: result[0] = carry
        
        return result if result[0] != 0 else result[1:]
    
    if __name__ == '__main__':
        L1 = [6, 4, 4]
        L2 = [7, 5, 6]
    
        print(sum_two_array(L1, L2))  # [1, 4, 0, 0]
    
        print(sum_two_array([6, 2, 4], [7, 5, 6]))  # [1, 3, 8, 0]
    
        print(sum_two_array([1, 2, 4], [8, 0]))     # [2, 0, 4]