So here is a code I have which attempts to add every element in a list irrespective of their lengths.
def elem_sum(lst1, lst2):
f_len = len(lst1) - (len(lst2) - 1)
for i in range(0, len(lst2), 1):
if f_len - i >= len(lst1):
break
else:
lst1[i] = lst1[i] lst2[i]
return lst1
When certain inputs such as elem_sum([1, 2, 3], [10, 20])
are provided,
the output correctly returns [11, 22, 3]
While other inputs such as elem_sum([1, 2, 3], [10, 20, 30, 40])
the output returns error.
What should I change here to make sure my code works for any given set of inputs??
CodePudding user response:
One option that may be worth considering is to make use of an existing library routine to give you pairs of numbers from lists of unequal lengths. The zip_longest
function in the itertools
package will do this, giving a sequence of tuples. After the end of one of the lists is reached, the missing values will be filled out using the specified fill value, which defaults to None
but you can pass your own fill value.
For example,
from itertools import zip_longest
lst1 = [1, 2, 3]
lst2 = [10, 20, 30, 40]
for t in zip_longest(lst1, lst2, fillvalue=0):
print(t)
gives:
(1, 10)
(2, 20)
(3, 30)
(0, 40)
So you could just write your function to use a list comprehension that calculates the sum of each of these tuples:
from itertools import zip_longest
def elem_sum(lst1, lst2):
return [sum(t) for t in zip_longest(lst1, lst2, fillvalue=0)]
print(elem_sum([1, 2, 3], [10, 20, 30, 40]))
which gives:
[11, 22, 33, 40]
Provided that you are not using a very old version of Python, the itertools
package is in the standard Python library, so you do not need to install any add-on packages.
CodePudding user response:
You could just check the lengths and swap the lists if needed:
def elem_sum(lst1, lst2):
# Swap if needed
if len(lst1) < len(lst2):
lst1, lst2 = lst2, lst1
f_len = len(lst1) - (len(lst2) - 1)
for i in range(0, len(lst2), 1):
if f_len - i >= len(lst1):
break
else:
lst1[i] = lst1[i] lst2[i]
return lst1