2017-10-14 4 views

Répondre

3

Utilisation itertools.groupby():

In [1]: lst = [1,2,2,3,2,2,4,5,5,6,7] 

In [2]: from itertools import groupby 

In [3]: [next(g) for _,g in groupby(lst)] 
Out[3]: [1, 2, 3, 2, 4, 5, 6, 7] 
1

Ce problème est deux pointeur. Voici le code pseudo:

start = 0 
end = 1 
while(end < len(arr)): 
    if(arr[end] != arr[start]): 
     arr[start + 1] = arr[end] 
     start += 1 
    end += 1 
# end of while loop 

# now arr[0... start] holds the result 

complexité du temps O(n) avec un espace constant.

0

Une autre méthode utilisant zip:

>>> a = [1, 2, 2, 3, 2, 2, 4, 5, 5, 6, 7] 
>>> [i for i,j in zip(a, a[1:] + [not a[-1]]) if i != j] 
[1, 2, 3, 2, 4, 5, 6, 7]