arrays - sum two lists element-by-element in python recursively -
this question has answer here:
- element-wise addition of 2 lists? 12 answers
is possible recursively sum 2 lists element element , return new list?
def sumlistelements(listone, listtwo): list = [] = 0 while < len(listone): list.append(listone[i] + listtwo[i]) += 1 return list
so,
a = [1, 2, 3] b = [3, 4, 5]
results
r = [4, 6, 8]
here recursive implementation
def recursive_sum(l1, l2, idx = 0): if idx < min(len(l1), len(l2)): return [l1[idx] + l2[idx]] + recursive_sum(l1, l2, idx + 1) else: return [] print recursive_sum([1, 2, 3], [4, 5, 6]) # [5, 7, 9]
or
def recursive_sum(l1, l2, result = none, idx = 0): if result none: result = [] if idx < min(len(l1), len(l2)): result.append(l1[idx] + l2[idx]) return recursive_sum(l1, l2, result, idx + 1) else: return result
Comments
Post a Comment