473,287 Members | 1,419 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,287 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 1555
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...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

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.