Compress a string

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Tue May 20 04:29:45 EDT 2008


Matt Porter a écrit :
> Hi guys,
> 
> I'm trying to compress a string.
> E.g:
>  "AAAABBBC" -> "ABC"
> 
> The code I have so far feels like it could be made clearer and more 
> succinct, but a solution is currently escaping me.
> 
> 
> def compress_str(str):

using 'str' as an indentifier will shadow the builtin str type.

>     new_str = ""
>     for i, c in enumerate(str):
>         try:
>             if c != str[i+1]:
>                 new_str += c
>         except IndexError:
>             new_str += c
>     return new_str
> 
> 

Now everyone gave smart solutions, may I suggest the stupidier possible one:

def compress_string(astring):
    compressed = []
    for c in astring:
        if c not in compressed:
            compressed.append(c)
    return ''.join(compressed)

Not elegant, but at least very clear.



More information about the Python-list mailing list