473,765 Members | 2,066 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

time consuming loops over lists

X-No-Archive: yes
Can some one help me improve this block of code...this jus converts the
list of data into tokens based on the range it falls into...but it
takes a long time.Can someone tell me what can i change to improve
it...

def Tkz(tk,data):
no_of_bins = 10
tkns = []
dmax = max(data)+1
dmin = min(data)
rng = ceil(abs((dmax - dmin)/(no_of_bins*1.0 )))
rngs = zeros(no_of_bin s+1)
for i in xrange(no_of_bi ns+1):
rngs[i] = dmin + (rng*i)
for i in xrange(len(data )):
for j in xrange(len(rngs )-1):
if data[i] in xrange(rngs[j],rngs[j+1]):
tkns.append( str(tk)+str(j) )
return tkns

Jul 19 '05 #1
8 1380
qu*****@gmail.c om wrote:
X-No-Archive: yes
Can some one help me improve this block of code...this jus converts the
list of data into tokens based on the range it falls into...but it
takes a long time.Can someone tell me what can i change to improve
it...

if data[i] in xrange(rngs[j],rngs[j+1]):


That's a bummer: You create a list and then search linearily in in -
where all you want to know is

if rngs[j] <= data[i] < rngs[j+1]

Attached is a script that does contain your old and my enhanced version
- and shows that the results are equal. Running only your version takes
~35s, where mine uses ~1s!!!

Another optimization im too lazy now would be to do sort of a "tree
search" of data[i] in rngs - as the ranges are ordered, you could find
the proper one in log_2(len(rngs) ) instead of len(rngs)/2.

Additional improvements can be achieved when data is sorted - but that
depends on your application and actually sizes of data.

Diez

from math import *
from Numeric import *
from random import *
def Tkz2(tk,data):
no_of_bins = 10
tkns = []
dmax = max(data)+1
dmin = min(data)
rng = ceil(abs((dmax - dmin)/(no_of_bins*1.0 )))
rngs = zeros(no_of_bin s+1)
for i in xrange(no_of_bi ns+1):
rngs[i] = dmin + (rng*i)
for i in xrange(len(data )):
for j in xrange(len(rngs )-1):
if rngs[j] <= data[i] < rngs[j+1]:
tkns.append( str(tk)+str(j) )
return tkns

def Tkz(tk,data):
no_of_bins = 10
tkns = []
dmax = max(data)+1
dmin = min(data)
rng = ceil(abs((dmax - dmin)/(no_of_bins*1.0 )))
rngs = zeros(no_of_bin s+1)
for i in xrange(no_of_bi ns+1):
rngs[i] = dmin + (rng*i)
for i in xrange(len(data )):
for j in xrange(len(rngs )-1):
if data[i] in xrange(rngs[j], rngs[j+1]):
tkns.append( str(tk)+str(j) )
return tkns
data = range(20,12312)
shuffle(data)
res1 = Tkz('A', data)
res2 = Tkz2('A', data)

print res1 == res2

Jul 19 '05 #2
wow i dint know that a single statement like that would make such a
difference. Thanks you very much. that really improves the performance

Jul 19 '05 #3
qu*****@gmail.c om wrote:
Can some one help me improve this block of code...this jus converts the
list of data into tokens based on the range it falls into...but it
takes a long time.Can someone tell me what can i change to improve
it...

def Tkz(tk,data):
no_of_bins = 10
tkns = []
dmax = max(data)+1
dmin = min(data)
rng = ceil(abs((dmax - dmin)/(no_of_bins*1.0 )))
rngs = zeros(no_of_bin s+1)
for i in xrange(no_of_bi ns+1):
rngs[i] = dmin + (rng*i)
for i in xrange(len(data )):
for j in xrange(len(rngs )-1):
if data[i] in xrange(rngs[j],rngs[j+1]):
tkns.append( str(tk)+str(j) )
return tkns


Use bisect(), e. g., with a slightly modified function signature:

from __future__ import division
import bisect
from math import ceil

def tkz(tk, data, no_of_bins=10):
dmax = max(data) + 1
dmin = min(data)
rng = ceil((dmax - dmin)/no_of_bins)
rngs = [dmin + rng*i for i in xrange(1, no_of_bins+1)]
tokens = [tk + str(i) for i in xrange(no_of_bi ns)]
return [tokens[bisect.bisect(r ngs, v)] for v in data]

if __name__ == "__main__":
print tkz("token_", [5, 7, 8, 9, 70, 200])

What are the tokens for, by the way? I'd recommend using the indices
directly if possible.

Peter

Jul 19 '05 #4
On Tue, 07 Jun 2005 18:13:01 +0200, "Diez B. Roggisch" <de***@web.de >
wrote:
Another optimization im too lazy now would be to do sort of a "tree
search" of data[i] in rngs - as the ranges are ordered, you could find
the proper one in log_2(len(rngs) ) instead of len(rngs)/2.


I don't see a "break" so why the "/2" ? also IIUC the
ranges are more than just ordered... they're all equal
and computed by

for i in xrange(no_of_bi ns+1):
rngs[i] = dmin + (rng*i)

so my guess is that instead of searching with

for j in xrange(len(rngs )-1):
if rngs[j] <= data[i] < rngs[j+1]:

one could just do

j = int((data[i] - dmin)/rng)

The code with this change gets roughly about twice faster.

Andrea
Jul 19 '05 #5
> I don't see a "break" so why the "/2" ? also IIUC the

That was the assumption of an equal distribution of the data. In
O-notationn this would be O(n) of course.
Diez
Jul 19 '05 #6
Diez B. Roggisch wrote:
qu*****@gmail.c om wrote:
X-No-Archive: yes
Can some one help me improve this block of code...this jus converts the
list of data into tokens based on the range it falls into...but it
takes a long time.Can someone tell me what can i change to improve
it...


if data[i] in xrange(rngs[j],rngs[j+1]):


That's a bummer: You create a list and then search linearily in in -
where all you want to know is

if rngs[j] <= data[i] < rngs[j+1]

Attached is a script that does contain your old and my enhanced version
- and shows that the results are equal. Running only your version takes
~35s, where mine uses ~1s!!!

Another optimization im too lazy now would be to do sort of a "tree
search" of data[i] in rngs - as the ranges are ordered, you could find
the proper one in log_2(len(rngs) ) instead of len(rngs)/2.

Additional improvements can be achieved when data is sorted - but that
depends on your application and actually sizes of data.

Diez

[snip]
Make these changes/additions:
=============== =============== =============== ====
# from Numeric import *
# +1 for Overkill-of-the-Year
def zeros(n):
return n * [0.0]

def Tkz3(tk, data, no_of_bins):
# indent 5 ???????
# change other funcs to have no_of_bins as an arg
tkns = []
dmax = max(data)+1
dmin = min(data)
rng = int(ceil(abs((d max - dmin)/(no_of_bins*1.0 ))))
for datum in data:
j = (datum - dmin) // rng
tkns.append( str(tk)+str(j) )
return tkns

for func in (Tkz, Tkz2, Tkz3):
t0 = time.time()
result = func('A', data, nbins)
t1 = time.time()
results.append( result)
print "function %s took %.2f seconds to produce %d tokens" %
(func.__name__, t1 - t0, len(result))

allsame = results [0] == results[1] == results[2]
print "\nIdentica l results:", allsame
=============== =============== =============== ==========
and get this:

C:\junk>ranges. py
C:\junk\ranges. py:46: DeprecationWarn ing: integer argument expected, got
float
if data[i] in xrange(rngs[j], rngs[j+1]):
function Tkz took 12.13 seconds to produce 12292 tokens
function Tkz2 took 0.08 seconds to produce 12292 tokens
function Tkz3 took 0.02 seconds to produce 12292 tokens

Identical results: True

=============== =============== =============== =====
using Python 2.4.1 (win32) on a 3.2Ghz Intel P4
=============== =============== =============== =====

Notes: (1) The OP's code as well as being deliciously O(N**2) depends on
the data beint *integers* -- otherwise it goes rapidly pear-shaped; see
the deprecation warning above, and try running it with data = [0.00001*
x for x in range(20, 12312)]. Consequently the use of math.* is a /mild/
overkill.

(2) The OP's code produces bins of equal nominal width but depending in
the range, the population of the last bin may be much less than the
population of the other bins. Another way of doing it would be to
produce bin widths so that the populations were more evenly spread. In
any case determining the appropriate bin could still be done by formula
rather than by searching.

Cheers,
John
Jul 19 '05 #7
On Tue, 07 Jun 2005 23:38:29 +0200, "Diez B. Roggisch" <de***@web.de >
wrote:
I don't see a "break" so why the "/2" ? also IIUC the


That was the assumption of an equal distribution of the data. In
O-notationn this would be O(n) of course.


It was a joke ... the issue is that there was no break
statement :-) i.e. your code kept searching even after
finding the proper range!

Actually that break (with 10 bins) is not terribly
important because the cost of the comparision is
small compared to the cost of append. The timings
I got are..

your code 1.26 sec
adding break 0.98 sec
direct index computation 0.56 sec

10 bins are so few that with just low-level speedups
(i.e. precomputing a list of ranges and str(j)) the
code that does a linear scan requires just 0.60 seconds.

Hand optimizing the direct computation code the
execution time gets down to 0.3 seconds; the inner loop
i used is:

for i, x in enumerate(data) :
j = int((x - dmin)/rng)
tkns[i] = tks + js[j]

with data = range(20, 123120)
Andrea
Jul 19 '05 #8
qu*****@gmail.c om wrote:
X-No-Archive: yes
Can some one help me improve this block of code...this jus converts the
list of data into tokens based on the range it falls into...but it
takes a long time.Can someone tell me what can i change to improve
it...

def Tkz(tk,data):
no_of_bins = 10
tkns = []
dmax = max(data)+1
dmin = min(data)
rng = ceil(abs((dmax - dmin)/(no_of_bins*1.0 )))
rngs = zeros(no_of_bin s+1)
for i in xrange(no_of_bi ns+1):
rngs[i] = dmin + (rng*i)
for i in xrange(len(data )):
for j in xrange(len(rngs )-1):
if data[i] in xrange(rngs[j],rngs[j+1]):
tkns.append( str(tk)+str(j) )
return tkns


On second thought, with bins of equal size you have an option that is even
faster than bisect:

def bins_calc(tk, data, no_of_bins=10):
dmax = max(data) + 1
dmin = min(data)
delta = dmax - dmin
rng = int(ceil((dmax - dmin)/no_of_bins))
tokens = [tk + str(i) for i in xrange(no_of_bi ns)]
return [tokens[(v-dmin)//rng] for v in data]

Peter

Jul 19 '05 #9

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

Similar topics

9
2142
by: Adrian Dragomirescu | last post by:
Hello, I have the following problem: In my ASPX page is a button called "Import". The action of this button is to import a set of data in my database. I have to import big datasets and this opperation is time consuming (aproximativelly 3-4 hours). After an hour my page display the error: "The page cannot be displayed
1
914
by: Eirik Eldorsen | last post by:
I have two scripts that take long time to run. One take about 10 mins, and the other takes 15 hours. By setting
5
1655
by: z. f. | last post by:
Hi, i have a vb.net windows application that makes HTTP requests with the framework's HttpWebReqeuest object. i have about 10 different requests that takes between 30 to 500 for the Request.GetResponse function to execute. this is acceptable. problem is that for 1 of the 10 urls i request, when i call the responseBody = reader.ReadToEnd() & "" it takes about 11.50 seconds (!) to execute and return the responseBody.
6
2176
by: veenakj | last post by:
Hi, I have a asp.net webpage which has aroud 20 steps as hyperlink. when start button is clicked, then step1 starts which does some operation in db and returns some value, based on that value i post the same page again to execute the next step. This continues untill the 20th step is executed. Now some steps, take lot of time to execute some queries(9 million row updates) in the database. So asp.net stops responding and do not continue...
1
1249
by: veenakj | last post by:
Hi, We use ASP.NET framework v1.1.4322, ADO.NET and Oracle 9i Database. This problem is with only with method which takes long time executing a proc in database. In a ASP.NET page_load method we call a database proc which executes for approximately for 30minutes.
2
5775
by: rdemyan via AccessMonster.com | last post by:
My application has a lot of complicated SQL statements, calculations, processing that takes time. I've created a custom form to act like a messagebox. It has 10 small rectangles on it that change color sequentially to let the user know that processing is occurring. This 'animation' occurs via the form timer event. However, I'm having trouble getting the animation to occur for all types of processing events. It appears that I have to...
9
4490
by: Kadett | last post by:
Hi all, I have following problem: I'm creating a ListView (Details) control at run-time and filling it with some records (let's say 10 000). This operation seems to be quite fast, but when I call Controls.Add(list), where list is my ListView control, then program hangs for minute. It seems like this time depends on number of records added to control. So probably when adding control to my form, those records are actualy added at this time...
1
5587
by: vikrant2108243 | last post by:
i wanna know some creative,easier and less time consuming ideas for creating project. i am a new user...
0
9404
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
10007
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
9959
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
9835
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
8833
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
6649
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
5277
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3926
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
3
2806
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.