Kitty Kitty - 6 months ago 3
Python Question

Python: while loop to a recursive function


how do i change this code to recursive? removes duplicated adjacent elements


def remove_adjacent(nums):
i = 1
while i < len(nums):
if nums[i] == nums[i-1]:
i -= 1
i += 1
return nums


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
        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.