Algorithm help per favore

Matt Shomphe MatthewS at HeyAnita.com
Thu Jun 19 04:28:00 CEST 2003


wrbt at email.com (Larry) wrote in message news:<2ec1bc1c.0306180746.159679d6 at posting.google.com>...
> I need to take a list (probably 20k to 40k elements) of numbers and
> remove consecutive duplicates. Non consecutive duplicates are ok.
> 
> Example: [6,3,3,3,5,7,6,3,4,4,3] => [6,3,5,7,6,3,4,3]
> 
> The 3 and 6 can appear more than once in the result set because
> they're separated by another value. Obviously this is trivial to
> accomplish by walking thru the list and building a new one (or yanking
> elements out of the existing one) but I'm curious if anyone knows of a
> more clever way, with speed being a goal more than memory usage.

This requires having access to the enumerate() function (which is
built-in in 2.3).  Not sure about speed, but it *is* a one liner:
>>> l = [6,3,3,3,5,7,6,3,4,4,3]
>>> [x for i,x in enumerate(l) if l[i-1] != x or i == 0]
[6, 3, 5, 7, 6, 3, 4, 3]




More information about the Python-list mailing list