Kitty - 1 year ago 51

Python Question

**problem**

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

**code**

`def remove_adjacent(nums):`

i = 1

while i < len(nums):

if nums[i] == nums[i-1]:

nums.pop(i)

i -= 1

i += 1

return nums

Answer

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.

Source (Stackoverflow)