In: Computer Science
Below is the code i got from another expert Q&A but im not allowed to use 'del' function because i didnt learn it.
+ I need to use recursion not list comprehenshion.
Please carefully go over the instructions
def add(vals1,vals2):
if (len(vals1))==0:
return []
else:
x =
vals1[0]+vals2[0]
del
vals1[0],vals2[0]
return [x]+add(vals1,vals2)
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: 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) 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 arithmetic operators: +, -, *, **, /, //, % boolean operators: <, >, <=, >=, ==, != comments and docstrings conditional statements: if, elif, else len() logical operators: and, or, not list operations: indexing, slicing, skip-slicing, concatenation, construction print() recursion string operations: indexing, slicing, concatenation, duplication type() def add(vals1,vals2):
Here is the code to do so.
The codes are well commented and easy to understand, if the answer helped you please upvote and if you have any doubts please comment i will surely help. please take care of the indentation while copying the code. Check from the screenshots provided.
Code:
def addLists(list1, list2):
# When the list size is 0, i.e. the end of recursion is
achieved
# return an empty list
if len(list1)==0:
return []
else:
# if the end of the list is not reached, concatenate the sum of
the
# first element of both lists to result, by performing a
recursive
# call on the lists starting from the next position
return [list1[0] + list2[0]] + addLists(list1[1:],list2[1:] )
print(addLists([1, 3, 4, 2, 5],[1,2,3,4,5]))