ilearnthis
ilearnthis

Reputation: 13

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

#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]))

Upvotes: 1

Views: 128

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51683

Your problem is that after creating the string from a negative number you try to convert something like ['-','5', ...] to int. Single '-' cannot be converted to int.


You can essentially do this with far less code then you did:

def toArr(num):
    """Returns list of digits (as ints) of a number, handling negatives correctly."""
    negative = num < 0
    nums = list(map(int, str(abs(num))))
    if negative:
        nums[0] *= -1
    return nums

def sum_arrays(arr1, arr2):
    # handle one or two empty inputs 
    if not arr1 or not arr2:
        return arr1 or arr2
    # do the work
    return toArr(int(''.join(map(str, arr1))) + int(''.join(map(str, arr2))))

print(sum_arrays([-7,9,8,2],[9,9,9]))
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]))

Output:

[-6, 9, 8, 3] 
[3, 4, 1]
[5, 9, 6]
[]
[-7, 8]
[-9, 6, 2, 6]

Output:

[-6, 9, 8, 3]

Explanations of int(''.join(map(str, arr1))) + int(''.join(map(str, arr2))):

This does the same thing twice:

  • convert each single number of the input array (arr1 / arr2) to strings
  • concattenate the strings
  • convert to int
  • add it to the same for the other array

The result is an integer that is then fed to toArr which

  • decides if the number is negative
  • converts the numbers absolute values to strings and converts each digit to an integer
  • fixes the first number to be negative if needed

Upvotes: 0

coderoftheday
coderoftheday

Reputation: 2075

Just convert the list to a string and remove the ,, [ and ]. Then convert them back to integers, and perform the operation.

def sum_arrays(array1,array2):
    if array1 == [] and array2 == []:
        return []
    elif array1 == []:
        return array2
    elif array2 == []:
        return array1
    else:
        a = str(array1).replace(', ','').replace('[','').replace(']','')
        b = str(array2).replace(', ','').replace('[','').replace(']','')
        summ = int(a) + int(b)
        
return [int('-'+x) if n == 1 else int(x) for n,x in enumerate(str(summ)) if x.isdigit()] if '-' in str(summ) else [int(x) for x in str(summ) if x.isdigit()]


print(sum_arrays([3,2,6,6],[-7,2,2,8]))

>>> [-3, 9, 6, 2]

Upvotes: 0

Related Questions