The error comes when the sum of the numbers is negative, because the – causes an error because data isn’t the same type of date

  arrays, function, list, python

#My task is to create a function called sum_arrays(), which takes two arrays consisting of integers, and #returns the sum of those two arrays.

#The twist is that (for example) [3,2,9] does not equal 3 + 2 + 9, it would equal ‘3’ + ‘2’ + ‘9’ #converted to an integer for this kata, meaning it would equal 329. The output should be an array of the #the sum in a similar fashion to the input (for example, if the sum is 341, you would return [3,4,1])

#[3,2,6,6],[-7,2,2,8] –> [-3,9,6,2] # 3266 + (-7228) = -3962

def sum_arrays(array1,array2):
    i = ""
    a = ""
    b = []
    if array1 == [] and array2 == []:
        return []
    elif array1 == []:
        return array2
    elif array2 == []:
        return array1
    else:
        for x in array1:
            i += str(x)
        for y in array2:
            a += str(y)
        sum = int(i) + int(a)
        if sum > -1:
            word = str(sum)
            for z in word:
                p = int(z)
                b.append(p)
            return b
        else:
            word = str(sum)
            for z in word[1:]:
                p = int(z)
                b.append(p)
                l = b[0] * -1
                b.append(l)
            return b[1:-1]

print(sum_arrays([3, 2, 9], [1, 2]))
print(sum_arrays([4,7,3],[1,2,3]))
print(sum_arrays([],[]))
print(sum_arrays([-9, 8],[0, 2, 0]))
print(sum_arrays([-9, 8, 3, 4],[0, 2, 0, 8]))

Source: Python Questions

LEAVE A COMMENT