473,699 Members | 2,693 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1185
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.maketran s() (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.maketran s('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='asdfbas df'
data.translat e(string.maketr ans('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.maketran s() (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.maketran s('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(pa t, 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(tab le)
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='asdfbas df'
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.maketran s() (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************ *********@m73g2 000cwd.googlegr oups.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(ol d, 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(pa t, 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(p at, 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(tab le)
print data.translate( table_str)

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

Marc 'BlackJack' Rintsch wrote:
In <11************ *********@m73g2 000cwd.googlegr oups.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(ol d, 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
2128
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 construct a checkbox array in a survey form where one of the choices is "No Preference" which is checked by default. If the victim chooses other than "No Preference", I'd like to uncheck
4
28443
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. all comments are appreciated. Thanks all. -Hari
0
1640
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.. -- N0 Spam Ema|l address. Please, when replying directly, delete "NSPAMO" from email address. Thanks
5
2033
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 reads this pickled file and writes an XML file with list of tables and fields (... next step will the module who creates the tables according to details found in the XML file). If anyone has some minutes to spare, suggestions and comments would be...
3
1752
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 get it up and running. I then run winmysqladmin V1.4 (the mysql service is running) When I go to databases inside the admin, it shows on the left side the name of the server and IP address and it has a 'test' database listed below it..... From...
3
1828
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 construct a checkbox array in a survey form where one of the choices is "No Preference" which is checked by default. If the victim chooses other than "No Preference", I'd like to uncheck
1
1551
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 did: shell> mysql -u root mysql> SET PASSWORD FOR ''@'localhost' = PASSWORD('newpwd'); .....as per instructed (I just cut 'n paste). I then quit mysql and log back on as root:
4
1441
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 learned to love content addressability in MATLAB. I was wondering it there's a simple routine (I think I can write a recurisve routine to do this.) to scan all the elements of a list, descending to lowest level and change something. What I'd like...
6
1680
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 another value. I want to use this returned value to sort the lists. So, my resultant list would be ordered by the return value of the
2
5878
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 .swf file to continuously loop, secondly i need this same file to play on every page visited on the site. I've researched and tried to just follow examples but each time there's no loop. The file plays once every time the page loads and then ends. ...
0
8686
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8615
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9173
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8882
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7748
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6533
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5872
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4627
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3057
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.