Question: Write a function double_final(n, values) that takes as inputs an integer n and an arbitrary list of integers values and that uses recursion to create
Write a function double_final(n, values) that takes as inputs an integer n and an arbitrary list of integers values and that uses recursion to create and return a version of values in which only the final occurrence of n (if any) has been doubled. For example: >>> double_final(3, [2, 3, 1, 2, 3, 5]) result: [2, 3, 1, 2, 6, 5]) >>> double_final(2, [2, 3, 1, 2, 3, 5]) result: [2, 3, 1, 4, 3, 5] >>> double_final(7, [9, 5, 7, 7, 7]) result: [9, 5, 7, 7, 14]) >>> double_final(2, [1, 3, 5, 7, 9]) # no occurrences result: [1, 3, 5, 7, 9] >>> double_final(2, []) result: []
Here is my code:
def double_final(n, values): """ takes as inputs an integer n and an arbitrary list of integers values and that uses recursion to create and return a version of values in which only the final occurrence of n (if any) has been doubled. """ if values==[]: return [] elif n==values[-1]: return (values[:-1]) else: double_final_rest=double_final(n,values [1:]) if values[0]==n: return [values[0]*2]+ double_final_rest else: return [values[0]]+ double_final_rest
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
