473,378 Members | 1,364 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

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(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
This is shorter and perhaps clearer:

def compress_str(str):
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(str):
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


Jun 27 '08 #1
1 1560
On May 18, 1:45*pm, Gary Herron <gher...@islandtraining.comwrote:
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 = "aaaaaaaaaaabbbbbbbbbbdddddaaaaaaaddddddcccccc c"
newstr = "".join( b for a,b in izip(" "+instr,instr) if a!=b )
print newstr
abdadc

-- Paul

Jun 27 '08 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: José Carlos | last post by:
Hi. How i could compress string of data?. I heart that it´s possible to make with librep, but i´dont know the way to do it. if somebody know any way to do it or any web where explain it i...
0
by: Patrick Questembert | last post by:
I am developping with Visual Studio 2003 + C# + MySQL 4.1 and the OleDb components. My problem is that a stament using the COMPRESS() function seems to work or not depending on the data ... Here...
3
by: Edward | last post by:
Thanks to Bob Powel (http://www.bobpowell.net/onebit.htm) I'm able to compress an image. However, this method takes a long time to compress an image. Does anyone know a quicker way? (The images I...
3
by: delphiconsultingguy | last post by:
Anybody? thanks, Sean
14
by: Hugh Janus | last post by:
Hi all, I have several *long* strings (see bottom of post for an example) which I will be sending across a network. Therefore, I want to compress them for speed and because later they will be...
6
by: Champika Nirosh | last post by:
Hi, I have two machine where I needed to have a extended TCP/IP protocol to make the link between the two machines Mean,I need to write a application that compress every data the machine send...
6
by: Adriano | last post by:
Can anyone recommend a simple way to compress/decomress a String in .NET 1.1 ? I have a random string of 70 characters, the output from a DES3 encryption, and I wish to reduce the lengh of it, ...
0
by: vampire1986 | last post by:
Hi all. I have project compress file using C#. I'm using name space IO.Compression and i saw this code on Internet but it is compress to file bigger than source file. Can you help me, please.Thanks...
0
by: J. Clifford Dyer | last post by:
On Sun, May 18, 2008 at 07:06:10PM +0100, Matt Porter wrote regarding Compress a string: def compress_str(s): # str is a builtin keyword. Don't overload it. out = for c in s: if out and c ==...
0
by: Matt Porter | last post by:
On Sun, 18 May 2008 19:13:57 +0100, J. Clifford Dyer <jcd@sdf.lonestar.orgwrote: Thanks. Had to change a few bits to make it behave as I expected: def compress_str(s): # str is a builtin...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.