On Sun, 18 May 2008 19:13:57 +0100, J. Clifford Dyer
<[EMAIL PROTECTED]> wrote:
On Sun, May 18, 2008 at 07:06:10PM +0100, Matt Porter wrote regarding
Compress a string:
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):
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
def compress_str(s):
# str is a builtin keyword. Don't overload it.
out = []
for c in s:
if out and c == out[-1]:
out.append(c) # This is faster than new_str += c
return ''.join(out)
Thanks. Had to change a few bits to make it behave as I expected:
def compress_str(s):
# str is a builtin keyword. Don't overload it.
out = [s[0],]
for c in s:
if out and c != out[-1]:
out.append(c) # This is faster than new_str += c
return ''.join(out)
Feels slightly less hacked together
--
http://mail.python.org/mailman/listinfo/python-list
--
--
--
http://mail.python.org/mailman/listinfo/python-list