I need a function negate_last(n, values) that takes an integer input of n and an arbitrary list of integers values and uses recursion to negate the last occurrence of n. I have tried to code the following lines, but the function returns the list with all of the element n in the list negated. How could I fix this function in order for it to only return the last occurrence of n in the list?
def negate_last(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 last occurrence of n (if any) has been negated. """
if values == []:
return []
else:
rest_part = negate_last(n, values[1:])
if values[0] == n:
result = [-1 * values[0]] rest_part
return result
else:
return [values[0]] rest_part
'''
CodePudding user response:
I am not sure if this was a solution, but what I so was to add a variable for validation outside the function and once the variable change to 1, then the next time a n appears it will not change. Hope it helps
validation = 0
def negate_last(n, values):
if values == []:
return []
else:
rest_part = negate_last(n, values[1:])
if values[0] == n:
if validation == 0:
result = [-1 * values[0]] rest_part
validation = 1
return result
else:
return [values[0]] rest_part
else:
return [values[0]] rest_part
CodePudding user response:
The below code should negate the last occurrence of n in the given array.
I think the issue in your code is that you are calling the recursive call for all non empty array which is negating all the occurrences of n. Instead if we find an occurrence (checking from right to get the last occurrence), we should treat that as a base case as we don't want to negate any more occurrences.
def negate_last(n, arr):
if not arr:
return []
if arr[-1] == n:
arr[-1] = -arr[-1]
return arr
return negate_last(n, arr[:-1]) [arr[-1]]
print(negate_last(5, [1, 2, 5, 4, 5]))