In: Computer Science
Write a function add(vals1, vals2) that takes as inputs two lists of 0 or more numbers, vals1 and vals2, and that uses recursion to construct and return a new list in which each element is the sum of the corresponding elements of vals1 and vals2. You may assume that the two lists have the same length. For example: >>> add([1, 2, 3], [3, 5, 8]) result: [4, 7, 11] Note that: The first element of the result is the sum of the first elements of the original lists (1 + 3 –> 4). The second element of the result is the sum of the second elements of the original lists (2 + 5 –> 7). The third element of the result is the sum of the third elements of the original lists (3 + 8 –> 11).
Use recursion please / also please explain your codes for better understanding.
Python recursive function code for the problem is provided below, please comment if any doubts:
Note: The code indentation may lose on copying the code, please refer the code screenshot provided at the end if any such problems occurs.
Python code:
#the function definition
def add(vals1, vals2):
#if the lists are empty, return null
if(len(vals1)==0):
return []
#if list has some elements
else:
#add the first elements of the list
x = vals1[0]+ vals2[0];
#delete the both lists first entries
del vals1[0]
del vals2[0]
#call the function recursively
return [x] + add(vals1, vals2)
###function tests
print(add([1, 2, 3], [3, 5, 8]))
print(add([3, 2, 5, 6], [1, 5, 6, 8]))
Output Screenshot:
Code Screenshot: