Google Python Class | List Exercise –
Given a list of numbers, return a list where
all adjacent == elements have been reduced to a single element,
so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
modify the passed in list.
My solution using a new list is –
def remove_adjacent(nums):
a = []
for item in nums:
if len(a):
if a[-1] != item:
a.append(item)
else: a.append(item)
return a
The question even suggests that it could be done by modifying the passed in list. However, the python documentation warned against modifying elements while iterating a list using the for loop.
I am wondering what else can I try apart from iterating over the list, to get this done. I am not looking for the solution, but maybe a hint that can take me into a right direction.
UPDATE
-updated the above code with suggested improvements.
-tried the following with a while loop using suggested hints –
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
Use a generator to iterate over the elements of the list, and
yielda new one only when it has changed.itertools.groupbydoes exactly this.You can modify the passed-in list if you iterate over a copy: