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

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_bins+1)
for i in xrange(no_of_bins+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 1357
qu*****@gmail.com 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_bins+1)
for i in xrange(no_of_bins+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_bins+1)
for i in xrange(no_of_bins+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.com 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_bins+1)
for i in xrange(no_of_bins+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_bins)]
return [tokens[bisect.bisect(rngs, 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_bins+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.com 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((dmax - 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 "\nIdentical results:", allsame
================================================== =====
and get this:

C:\junk>ranges.py
C:\junk\ranges.py:46: DeprecationWarning: 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.com 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_bins+1)
for i in xrange(no_of_bins+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_bins)]
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
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...
1
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
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...
6
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...
1
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...
2
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...
9
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...
1
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
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
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
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,...
0
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,...
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...
0
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...
0
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,...
0
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...

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.