473,320 Members | 1,699 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,320 software developers and data experts.

looping question 4 NEWB

Hi,

I often have code like this:

data='asdfbasdf'
find = (('a','f')('s','g'),('x','y'))
for i in find:
if i[0] in data:
data = data.replace(i[0],i[1])

is there a faster way of implementing this? Also, does the if clause
increase the speed?

Thanks,
Matthew

Jul 6 '06 #1
8 1170
manstey schreef:
Hi,

I often have code like this:

data='asdfbasdf'
find = (('a','f')('s','g'),('x','y'))
for i in find:
if i[0] in data:
data = data.replace(i[0],i[1])

is there a faster way of implementing this? Also, does the if clause
increase the speed?
I think this is best done with translate() and string.maketrans() (see
http://docs.python.org/lib/node110.html#l2h-835 and
http://docs.python.org/lib/string-methods.html#l2h-208). An example:

import string

data = 'asdfbasdf'
translatetable = string.maketrans('asx', 'fgy')
data = data.translate(translatetable)
print data

This results in:

fgdfbfgdf

--
If I have been able to see further, it was only because I stood
on the shoulders of giants. -- Isaac Newton

Roel Schroeven
Jul 6 '06 #2
On 06.07.2006 12:43, manstey wrote:
Hi,

I often have code like this:

data='asdfbasdf'
find = (('a','f')('s','g'),('x','y'))
for i in find:
if i[0] in data:
data = data.replace(i[0],i[1])

is there a faster way of implementing this? Also, does the if clause
increase the speed?

Thanks,
Matthew
>>import string
data='asdfbasdf'
data.translate(string.maketrans('asx', 'fgy'))
'fgdfbfgdf'

HTH,
Wolfram
Jul 6 '06 #3
But what about substitutions like:
'ab' 'cd', 'ced' 'de', etc

what is the fastest way then?
Roel Schroeven wrote:
manstey schreef:
Hi,

I often have code like this:

data='asdfbasdf'
find = (('a','f')('s','g'),('x','y'))
for i in find:
if i[0] in data:
data = data.replace(i[0],i[1])

is there a faster way of implementing this? Also, does the if clause
increase the speed?

I think this is best done with translate() and string.maketrans() (see
http://docs.python.org/lib/node110.html#l2h-835 and
http://docs.python.org/lib/string-methods.html#l2h-208). An example:

import string

data = 'asdfbasdf'
translatetable = string.maketrans('asx', 'fgy')
data = data.translate(translatetable)
print data

This results in:

fgdfbfgdf

--
If I have been able to see further, it was only because I stood
on the shoulders of giants. -- Isaac Newton

Roel Schroeven
Jul 6 '06 #4
manstey:
is there a faster way of implementing this? Also, does the if clause
increase the speed?
I doubt the if increases the speed. The following is a bit improved
version:

# Original data:
data = 'asdfbasdf'
find = (('a', 'f'), ('s', 'g'), ('x', 'y'))

# The code:
data2 = data
for pat,rep in find:
data2 = data.replace(pat, rep)
print data2

# If find contains only chars, and the string is long
# enough, then this is more or less the faster solution:

from string import maketrans
table = map(chr, xrange(256))
for c1,c2 in find:
table[ord(c1)] = c2
table_str = "".join(table)
print data.translate(table_str)

Bye,
bearophile

Jul 6 '06 #5
manstey schreef:
Roel Schroeven wrote:
>manstey schreef:
>>I often have code like this:

data='asdfbasdf'
find = (('a','f')('s','g'),('x','y'))
for i in find:
if i[0] in data:
data = data.replace(i[0],i[1])

is there a faster way of implementing this? Also, does the if clause
increase the speed?
I think this is best done with translate() and string.maketrans() (see
http://docs.python.org/lib/node110.html#l2h-835 and
http://docs.python.org/lib/string-methods.html#l2h-208). An example:
But what about substitutions like:
'ab' 'cd', 'ced' 'de', etc

what is the fastest way then?
Ah, in that case I don't think you can do much better than you already
did. But I think the if clause doesn't increase the speed; it might even
decrease it. If you want to know for sure, use timeit to see what's fastest.

--
If I have been able to see further, it was only because I stood
on the shoulders of giants. -- Isaac Newton

Roel Schroeven
Jul 6 '06 #6
In <11*********************@m73g2000cwd.googlegroups. com>, manstey wrote:
I often have code like this:

data='asdfbasdf'
find = (('a','f')('s','g'),('x','y'))
for i in find:
if i[0] in data:
data = data.replace(i[0],i[1])

is there a faster way of implementing this? Also, does the if clause
increase the speed?
It decreases it. You search through `data` in the ``if`` clause. If it's
`False` then you have searched the whole data and skip the replace. If
it's `True` you searched into data until there's a match and the the
`replace()` starts again from the start and searches/replaces through the
whole data.

You can get rid of the indexes and make the code a bit clearer by the way:

for old, new in find:
data = data.replace(old, new)

Ciao,
Marc 'BlackJack' Rintsch
Jul 6 '06 #7
be************@lycos.com wrote:
manstey:
is there a faster way of implementing this? Also, does the if clause
increase the speed?

I doubt the if increases the speed. The following is a bit improved
version:

# Original data:
data = 'asdfbasdf'
find = (('a', 'f'), ('s', 'g'), ('x', 'y'))

# The code:
data2 = data
for pat,rep in find:
data2 = data.replace(pat, rep)
print data2
Small bug in that code, you'll wind up with data2 only being the result
of replacing the last (pat, rep) in find. It should be:

data2 = data
for pat, rep in find:
data2 = data2.replace(pat, rep)

Be careful with multi-char terms in find. You could wind up replacing
patterns that only occur in data2 as a result of earlier replacements.

I.e. if
find = ('bc', 'ab'), ('aa', 'bb')
data = 'abc'

then
data2 = 'aab' # First iteration,
data2 = 'bbb' # Second iteration replaces 'aa' even though 'aa' isn't
in original data.

Have fun,
~Simon

>
# If find contains only chars, and the string is long
# enough, then this is more or less the faster solution:

from string import maketrans
table = map(chr, xrange(256))
for c1,c2 in find:
table[ord(c1)] = c2
table_str = "".join(table)
print data.translate(table_str)

Bye,
bearophile
Jul 6 '06 #8
Thanks Marc, that was very helpful.

Marc 'BlackJack' Rintsch wrote:
In <11*********************@m73g2000cwd.googlegroups. com>, manstey wrote:
I often have code like this:

data='asdfbasdf'
find = (('a','f')('s','g'),('x','y'))
for i in find:
if i[0] in data:
data = data.replace(i[0],i[1])

is there a faster way of implementing this? Also, does the if clause
increase the speed?

It decreases it. You search through `data` in the ``if`` clause. If it's
`False` then you have searched the whole data and skip the replace. If
it's `True` you searched into data until there's a match and the the
`replace()` starts again from the start and searches/replaces through the
whole data.

You can get rid of the indexes and make the code a bit clearer by the way:

for old, new in find:
data = data.replace(old, new)

Ciao,
Marc 'BlackJack' Rintsch
Jul 9 '06 #9

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

Similar topics

0
by: claudel | last post by:
Hi I have a newb PHP/Javascript question regarding checkbox processing I'm not sure which area it falls into so I crossposted to comp.lang.php and comp.lang.javascript. I'm trying to...
4
by: Hari | last post by:
Basically I would like to downlod the visual basic 6.0 compiler, but i already have the vb.net compiler. I had to pay for the VB.net IDE, just wondering if I can get the vb 6.0 IDE for free or not....
0
by: David E. | last post by:
So as a programmer, what's the best thing to study? EJB? How much of the J2EE or Enterprise architecture is necessary to no? I guess I need a good overview for a newb like me... thanks.. --...
5
by: Alexandre | last post by:
Hi, Im a newb to dev and python... my first sefl assigned mission was to read a pickled file containing a list with DB like data and convert this to MySQL... So i wrote my first module which...
3
by: Walter | last post by:
But I'm stumped..... I've got a windows 2000 server and I am trying to set up PHPBB on it using a mysql database.. I am very inexperienced on this..... Ive installed mysql V4.0.20d and I can...
3
by: claudel | last post by:
Hi I have a newb PHP/Javascript question regarding checkbox processing I'm not sure which area it falls into so I crossposted to comp.lang.php and comp.lang.javascript. I'm trying to...
1
by: notbob | last post by:
Newb here! Using 4.0.20 on Slack. Slogging through the official manual. At 2.4.3 Securing the Initial MySQL Accounts, I'm finally stopped cold while trying to follow instructions. Here's what I...
4
by: Donald Newcomb | last post by:
I'm a real Python NEWB and am intrigued by some of Python's features, so I'm starting to write code to do some things to see how it works. So far I really like the lists and dictionaries since I...
6
by: Sean Berry | last post by:
Hello all I have build a list that contains data in the form below -- simplified for question -- myList = ,, ...] I have a function which takes value3 from the lists above and returns...
2
by: hayz | last post by:
Flash sound file looping problems hello there I'm definitely a newb so please bare some patience. I have a flash sound file on the index page of a site i'm working on. First off i need the...
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
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...
1
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: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
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)...
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...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

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.