In: Computer Science
This is the question
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:
And this is why i have for the code. But i have not learned del function and im afraid i cant use it.
im only allowed to use
def add(vals1,vals2):
"""return a new list in which each elements is
the sum of
the corresponding
elements of val1 and vals2
input: lists of 0 or
more numbers
"""
if (len(vals1))==0:
return []
else:
x =
vals1[0]+vals2[0]
del
vals1[0],vals2[0]
return [x]+add(vals1,vals2)
The function is as follows:
# Definition of the function.
def add(vals1, vals2):
# check the condition
if(len(vals1)==0):
# return empty array.
return []
else:
# calculate the value.
x = vals1[0]+ vals2[0];
# return the value recursively.
return [x] + add(vals1[1:], vals2[1:])
The complete executable code is as follows:
Program screenshots:
Sample Output:
Code to Copy:
# kindly use python 3.6
# kindly indent the code as given in above screenshot.
# Definition of the function.
def add(vals1, vals2):
# check the condition
if(len(vals1)==0):
# return empty array.
return []
else:
# calculate the value.
x = vals1[0]+ vals2[0];
# return the value recursively.
return [x] + add(vals1[1:], vals2[1:])
# call the function.
print(add([1, 2, 3], [3, 5, 8]))