473,748 Members | 2,793 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 1188
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
2130
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
28445
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
1643
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
2034
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
1760
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
1829
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
1554
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
1443
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
1684
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
5883
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
8991
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
8830
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
9370
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9321
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9247
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
8242
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...
0
4874
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2782
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.