Yet another unique() function...

Paul Rubin http
Tue Feb 27 21:48:50 EST 2007


"MonkeeSage" <MonkeeSage at gmail.com> writes:
> Here's yet another take on a unique() function for sequences. It's
> more terse than others I've seen and works for all the common use
> cases (please report any errors on the recipe page):
> 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502263

That looks pretty messy, and it's a quadratic time algorithm (or maybe
worse) because of all the list.index and deletion operations.

This version is also quadratic and passes your test suite, but
might differ in some more complicated cases:

def unique(seq, keepstr=True):
    t = type(seq)
    if t==str:
        t = (list, ''.join)[bool(keepstr)]
    seen = []
    return t(c for c in seq if (c not in seen, seen.append(c))[0])



More information about the Python-list mailing list