Write a recursive function sum-pairs that takes the following arguments, in this
ID: 3594859 • Letter: W
Question
Write a recursive function sum-pairs that takes the following arguments, in this order: I. 1ist1: a list of of integers 2. list2: another list of integers The function recursively computes the pairwise sums of all elements from listl and list2, inserting each sum into a list that is returned by the function. If one list is shorter than the other, then the "extra" elements from the longer list are simply appended to the returned list. Pseudocode for the recursive call only: let x = the sum of the first two elements of the lists let y - a list containing the sums of all pairs of elements from the two lists, EXCEPT for the sum of the first pair insert the sum x y at the first position ofy return y Examples: Return Value [2, 4, 7 1, 2, 3, 4, 5] Function Call sum.pairs (0, 1, 71, 12, 311 sum.pairs(, [1, 2, 3, sum.pairs ([6, 7, 8, [15, 14, 13])21, 21, 21] 4, 51Explanation / Answer
def recursive_sum(list1, list2, idx = 0):
if idx < min(len(list1), len(list2)):
return [list1[idx] + list2[idx]] + recursive_sum(list1, list2, idx + 1)
else:
return []
print recursive_sum([1, 2, 3], [4, 5, 6])
print recursive_sum([0,1,7], [2,3])
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.