How can I refrain from using import and still get the same output from my function?

Viewed 48

So I'm trying to write a function elem_sum(lst1:List[int], lst2:List[int]) that takes 2 inputs as lists and returns the summation element-wise in lst1 and lst2. lst1 and lst2 might have different lengths. Suppose lst1 = [a, b, c] and lst2 = [d, e]. Your function should return [a+d, b+e, c].

Examples

elem_sum([1, 2, 3], [10, 20]) == [11, 22, 3]
elem_sum([1, 2, 3], [10, 20, 30, 40]) == [11, 22, 33, 40]
elem_sum([1], [2, 12]) == [3, 12]

Here's what I have tried, which works...

from itertools import zip_longest

def elem_sum(lst1, lst2):
    return [sum(t) for t in zip_longest(lst1, lst2, fillvalue=0)]

However, I want to find a solution which works without using itertools AND Import... what should I add or change in my code?

3 Answers

You need not use the itertools if you take the approach like below

def elem_sum(ls1, ls2):
    iter_list, other_list = (ls1, ls2) if len(ls1) < len(ls2) else (ls2, ls1)
    return [sum(x) for x in zip(iter_list, other_list)]+ other_list[len(iter_list):]

One approach could be to substitute zip_longest by the built-in zip function, but as you know it will just cut of the remaining elements of the longer array. So what you can do is to use zip and then just append the remaining elements of the longer array:

def elem_sum(lst1, lst2):
    shorter_length = min(len(lst1), len(lst2))
    return [sum(t) for t in zip(lst1, lst2)] + lst1[shorter_length:] + lst2[shorter_length:]

Using the indexing [shorter_length:] on the shorter array will just return an empty array. Thus, we can just concatenate them.

Append zeros to the shorter:

def elem_sum(l1, l2):
    len_1 = len(l1)
    len_2 = len(l2)
    max_len = max(len_1, len_2)
    min_len = min(len_1, len_2)
    for i in range(max_len-min_len):
        if len_2 < len_1:
            l2.append(0)
        if len_1 < len_2:
            l1.append(0)
    l_r = []
    for i in range(max_len):
        l_r.append(l1[i] + l2[i])
    return l_r


print(elem_sum([1, 2, 3], [10, 20]))
print(elem_sum([1, 2, 3], [10, 20, 30, 40]))
print(elem_sum([1], [2, 12]))

Output:

[11, 22, 3]
[11, 22, 33, 40]
[3, 12]
Related