Re: Compress a string

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Gary Herron

    Re: Compress a string

    Matt Porter wrote:
    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(st r):
    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
    >
    >
    Cheers
    Matt
    This is shorter and perhaps clearer:

    def compress_str(st r):
    new_str = ""
    for c in str:
    if not new_str or c != new_str[-1]:
    new_str += c
    return new_str


    However, successive appends to a string is inefficient (whereas
    successive appends to a list are ok), so this is probably more efficient:

    def compress_str(st r):
    r = []
    for c in str:
    if not r or c != r[-1]:
    r.append(c) # Build a list of characters
    return ''.join(r)# Join list into a single string


    And then building a list in a loop is usually more efficient (and
    perhaps clearer) if done with a list comprehension:

    new_str = ''.join([c for i,c in enumerate(str) if not i or str[i-1]
    != c])

    or, maybe clearer as two lines:

    r = [c for i,c in enumerate(str) if not i or str[i-1] != c]
    new_str = ''.join(r)


    Gary Herron






  • Paul McGuire

    #2
    Re: Compress a string

    On May 18, 1:45 pm, Gary Herron <gher...@island training.comwro te:
    Matt Porter wrote:
    Hi guys,
    >
    I'm trying to compress a string.
    E.g:
     "AAAABBBC" -"ABC"
    >
    I'm partial to using (i)zip when I need to look at two successive
    elements of a sequence:
    >>from itertools import izip
    >>instr = "aaaaaaaaaaabbb bbbbbbbdddddaaa aaaaddddddccccc cc"
    >>newstr = "".join( b for a,b in izip(" "+instr,ins tr) if a!=b )
    >>print newstr
    abdadc

    -- Paul

    Comment

    Working...