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

Need some help speeding up this loop

Hi all,

I'm trying to write a loop that will build a list of "template
strings".

My current implementation is *really slow*. It took 15 minutes to
finish. (final len(list) was about 16k entries.)

#combinations = 12 small template strings ie "{{ city }},
{{ state }}..."
#states = either a django model or a list of 50 states
#cities = either a django model of 400 cities or a smaller list of
cities.

templates = []
for c in combinations:
if len(states):
for state in states:
if type(geo) is City:
cities = state.city_set.all()
else:
cities = geo
for city in cities:
if type(city) is City:
city = city.city
templates.append(c.template.replace('{{ city }}',
city))
templates.append(c.template) #just in case there are no
cities
templates = [k.replace('{{ state }}',
state.state).replace('{{ state_abbr }}', state.abbreviation) for k in
templates]
elif len(geo):
for city in geo:
templates.append(c.template.replace('{{ city }}', city))
else:
#no cities or states so add roots
templates.append(c.template)

The final output needs to be a list of the templates combined with all
the states and cities (some templates will only have the city, some
only the state).

Any ideas how I can optimize this?

Thanks!
Oct 30 '08 #1
2 953
On Wed, 29 Oct 2008 19:24:32 -0700, erikcw wrote:
I'm trying to write a loop that will build a list of "template strings".

My current implementation is *really slow*. It took 15 minutes to
finish. (final len(list) was about 16k entries.)
What is `list` here? Do you mean ``len(templates)``?
templates = []
for c in combinations:
if len(states):
for state in states:
if type(geo) is City:
cities = state.city_set.all()
else:
cities = geo
for city in cities:
if type(city) is City:
city = city.city
templates.append(c.template.replace('{{ city }}',
city))
templates.append(c.template) #just in case there are no
cities
templates = [k.replace('{{ state }}',
state.state).replace('{{ state_abbr }}', state.abbreviation) for k in
templates]
It seems you are iterating over *all* accumulated templates so far, over
and over again, even those which don't have those place holders anymore.
Looks like the source of quadratic runtime for me.

Ciao,
Marc 'BlackJack' Rintsch
Oct 30 '08 #2
On Oct 30, 2:24*am, erikcw <erikwickst...@gmail.comwrote:
Hi all,

I'm trying to write a loop that will build a list of "template
strings".

My current implementation is *really slow*. *It took 15 minutes to
finish. (final len(list) was about 16k entries.)

#combinations = 12 small template strings ie "{{ city }},
{{ state }}..."
#states = either a django model or a list of 50 states
#cities = either a django model of 400 cities or a smaller list of
cities.

templates = []
for c in combinations:
* * if len(states):
* * * * for state in states:
* * * * * * if type(geo) is City:
* * * * * * * * cities = state.city_set.all()
* * * * * * else:
* * * * * * * * cities = geo
* * * * * * for city in cities:
* * * * * * * * if type(city) is City:
* * * * * * * * * * city = city.city
* * * * * * * * templates.append(c.template.replace('{{ city }}',
city))
* * * * * * templates.append(c.template) #just in case there are no
cities
* * * * * * templates = [k.replace('{{ state }}',
state.state).replace('{{ state_abbr }}', state.abbreviation) for k in
templates]
The line above does a lot of unnecessary work as you iterate over lots
of templates which have already been completely substituted.
* * elif len(geo):
* * * * for city in geo:
* * * * * * templates.append(c.template.replace('{{ city }}',city))
* * else:
* * * * #no cities or states so add roots
* * * * templates.append(c.template)

The final output needs to be a list of the templates combined with all
the states and cities (some templates will only have the city, some
only the state).

Any ideas how I can optimize this?

Thanks!
I would suggest this (untested):

def template_replace(template, values):
for var, val in values.iteritems():
template = template.replace('{{ %s }}' % var, val)
return template

templates = []
for c in combinations:
if len(states):
for state in states:
values = { 'state': state.state,
'state_abbr': state.abbreviation }
#just in case there are no cities :
templates.append(template_replace(c.template, values)
if type(geo) is City:
cities = state.city_set.all()
else:
cities = geo
for city in cities:
if type(city) is City:
values['city'] = city.city
# Do all the replacing in one go:
templates.append(template_replace(c.template,
values))
elif len(geo):
for city in geo:
templates.append(template_replace(c.template,
{'city':city}))
else:
#no cities or states so add roots
templates.append(c.template)

HTH

Even better would be to iterate over states, then cities, then only
templates.

--
Arnaud
Oct 30 '08 #3

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

Similar topics

5
by: joethis | last post by:
I have a query that returns a resultset rather fast, but when I go through the loop to write it out to the page I get a slow display. Is there a way to speed this up?
12
by: dvumani | last post by:
I have C code which computes the row sums of a matrix, divide each element of each row with the row sum and then compute the column sum of the resulting matrix. Is there a way I can speed up the...
3
by: Bruce D | last post by:
Here's the breakdown: MySQL 4.0.12 Table: Assignment (indexes are created on proper fields) 419,234 records Table: Finders (indexes are created on proper fields) 5,345,657 records My user wants...
3
by: Jon Skeet | last post by:
I'm trying to speed up a data migration tool I'm writing that uses COM interop. Currently I'm accessing each field within a record individually, which works, but means going across the...
2
by: simon_w3 | last post by:
Hi All, I'm trying to figure out how I can speed up a fragment of code (which has been converted from vb6 to .NET) that reads data from a database. My knowledge on database programming is...
5
by: Simon | last post by:
Hi All, I'm trying to figure out how I can speed up a fragment of code (which has been converted from vb6 to .NET) that reads data from a database. My knowledge on database programming is...
4
by: sigloiv | last post by:
Alright, this is my first post here, and I'm the most ignorant coder one may meet (I've only started a few months ago, and I rarely have time to learn anything new), but, as a class project, I'm...
4
by: jocknerd | last post by:
About 10 years ago, I wrote a C app that would read scores from football games and calculate rankings based on the outcome of the games. In fact, I still use this app. You can view my rankings at...
5
by: RobinAG | last post by:
Hello, I just split my database into front and back end. My front end users are experiencing really slow opening of forms. I've searched online for help speeding up forms, but I'm not sure what...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
0
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...
0
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...

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.