Python solve problem with string operation

John Gordon gordon at panix.com
Thu Jan 16 17:58:44 EST 2014


In <mailman.5609.1389912537.18130.python-list at python.org> Mark Lawrence <breamoreboy at yahoo.co.uk> writes:

> > input = "344111133311222223377"
> > output = []
> > previous_ch = None
> > for ch in input:
> >      if ch != previous_ch:
> >          output.append(ch)
> >          previous_ch = ch
> > print ''.join(output)
> >

> Cheat, you've used a list :)

Ack!  I missed that the OP doesn't want to use lists.

Well, let's try this instead:

    import sys

    input = "344111133311222223377"
    previous_ch = None
    for ch in input:
         if ch != previous_ch:
             sys.stdout.write(ch)
             previous_ch = ch
    sys.stdout.write('\n')

-- 
John Gordon         Imagine what it must be like for a real medical doctor to
gordon at panix.com    watch 'House', or a real serial killer to watch 'Dexter'.




More information about the Python-list mailing list