how do i change this code to recursive? removes duplicated adjacent elements
i = 1
while i < len(nums):
if nums[i] == nums[i-1]:
i -= 1
i += 1
You check for index
1, then recursively for the rest of the sequence. Having reached the end of the sequence is your base case:
def remove_adjacent(nums, i=1): if i >= len(nums): # base case: index has moved beyond end return nums if nums[i] == nums[i-1]: # if applicable: pop adjacent duplicate nums.pop(i) return remove_adjacent(nums, i=i) # if popped, do NOT increase index return remove_adjacent(nums, i=i+1) # since the function changes the argument sequence in place, you do not # really need to return. Calling the function will be enough ...
I assume that this is some kind of academic/training exercise to practice the concept of recursion. It should be pointed out that recursion does not improve readability in your case and hardly ever improves performance compared to an iterative solution.