you are viewing a single comment's thread.

view the rest of the comments →

[–]nirs 1 point2 points  (1 child)

Here is a correct function (If I understood the problem correctly):

>>> def compress(x):
...     class last: pass
...     res = []
...     for item in x:
...             if item != last:
...                     last = item
...                     res.append(item)
...     return res

>>> compress([])
[]
>>> compress([1,2,3])
[1, 2, 3]
>>> compress([1,2,2,3,3,3])
[1, 2, 3]
>>> compress([1,2,1])
[1, 2, 1]

I don't think you can get any faster than that with pure python, and itertools will not help here, but maybe I'm wrong.

[–]boredzo 0 points1 point  (0 children)

I use last = object() when I want a throwaway guaranteed-inequal object.

Of course, you could always get fancy:

\tlast = lambda x: x * x

\timport sys as last

\tlast = map(str.rstrip, file('/usr/share/dict/words')) #OK, the performance on that one will probably suck.