473,785 Members | 2,414 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

range() is not the best way to check range?

it seems that range() can be really slow:

the following program will run, and the last line shows how long it ran
for:

import time

startTime = time.time()

a = 1.0
for i in range(0, 30000):
if i in range (0, 10000):
a += 1
if not i % 1000: print i

print a, " ", round(time.time () - startTime, 1), "seconds"
---------------------------------
the last line of output is
---------------------------------

10001.0 22.8 seconds

so if i change the line

if i in range (0, 10000):

to

if i >= 0 and i < 10000:

the the last line is

10001.0 0.2 seconds

so approximately, the program ran 100 times faster!

or is there an alternative use of range() or something similar that can
be as fast?

Jul 18 '06
45 8576
John Machin wrote:
On 18/07/2006 12:41 PM, Su************@ gmail.com wrote:
it seems that range() can be really slow:
[...]
Some things to try:
1a. Read what the manual has to say about the range() function ... what
does it produce?
Indeed. Still, the addition of a __contains__ method to range (and
xrange) would permit acceptable performance for the code given. Perhaps
this is a convenience worth considering for future Python releases.

Paul

Jul 18 '06 #11

Su************@ gmail.com wrote:
it seems that range() can be really slow:
if i in range (0, 10000):
RTFM on range()

You're completely mis-using it here, using it with an if ... in ...
test. The purpose of range() in Python is as loop control, not
comparisons! It's not a SQL BETWEEN statement.

Although you _can_ do this (you've done it!) you've also found that
it's slow. Many people would argue that even using range() for loop
control is unusably slow.

Jul 18 '06 #12
Grant Edwards wrote:
Using xrange as somebody else suggested is also insane.
Sorry about that, I somehow got the misguided notion that xrange defines
its own __contains__, so that it would be about the same speed as using
comparison operators directly. I figured the OP might have a better
reason for wanting to use range() than his post mentioned -- perhaps the
range to check was being passed from a function, and it would be easier
to pass an object than a tuple of lower and upper bound -- but since
xrange does looping for a membership test, my suggestion was indeed insane.
Jul 18 '06 #13
On 18/07/2006 7:22 PM, Paul Boddie wrote:
John Machin wrote:
>On 18/07/2006 12:41 PM, Su************@ gmail.com wrote:
>>it seems that range() can be really slow:

[...]
>Some things to try:
1a. Read what the manual has to say about the range() function ... what
does it produce?

Indeed. Still, the addition of a __contains__ method to range (and
xrange) would permit acceptable performance for the code given. Perhaps
this is a convenience worth considering for future Python releases.
range() and xrange() are functions. You are suggesting that 2
*functions* should acquire a __contains__ method each? I trust not.

Perhaps you meant that the acquisitors should be the objects that those
functions return.

range() returns a list. Lists already have a __contains__ method. It's
been getting a fair old exercising in the last few hours, but here we go
again:
>python -mtimeit -s"x=range(30000 )" "x.__contains__ (40000)"
1000 loops, best of 3: 1.09 msec per loop
>python -mtimeit -s"x=range(30000 )" "40000 in x"
1000 loops, best of 3: 1.09 msec per loop
>python -mtimeit -s"x=range(30000 )" "x.__contains__ (1)"
1000000 loops, best of 3: 0.434 usec per loop
>python -mtimeit -s"x=range(30000 )" "1 in x"
1000000 loops, best of 3: 0.137 usec per loop

A __contains__ method for xrange objects? The case of x in xrange(lo,
hi) is met by lo <= x < hi. IMHO, anyone who wants x in xrange(lo, hi,
step) should be encouraged to do the necessary algebra themselves; I
wouldn't suggest that any core dev time be wasted on implementing such
folderol.

In any case, isn't the *whole* xrange gizmoid on GvR's I-wish-I-hadn't list?

Cheers,
John
Jul 18 '06 #14
John Machin wrote:
>
range() and xrange() are functions. You are suggesting that 2
*functions* should acquire a __contains__ method each? I trust not.
Well, range is a function in the current implementation, although its
usage is similar to that one would get if it were a class, particularly
a subclass of list or one providing a list-style interface. With such a
class, you could provide a __contains__ method which could answer the
question of what the range contains based on the semantics guaranteed
by a range (in contrast to a normal list).
Perhaps you meant that the acquisitors should be the objects that those
functions return.
The whole point was to avoid expanding the range into a list.

[...]
A __contains__ method for xrange objects? The case of x in xrange(lo,
hi) is met by lo <= x < hi. IMHO, anyone who wants x in xrange(lo, hi,
step) should be encouraged to do the necessary algebra themselves; I
wouldn't suggest that any core dev time be wasted on implementing such
folderol.
Sure, you could always implement your own class to behave like an
existing range and to implement the efficient semantics proposed above.
In any case, isn't the *whole* xrange gizmoid on GvR's I-wish-I-hadn't list?
Yes, he wants range to return an iterator, just like xrange more or
less does now. Given that xrange objects support __getitem__, unlike a
lot of other iterators (and, of course, generators), adding
__contains__ wouldn't be much of a hardship. Certainly, compared to
other notational conveniences bounced around on the various development
lists, this one would probably provide an order of magnitude
improvement on the usual bang per buck development ratio.

Paul

Jul 18 '06 #15
Andy Dingley wrote:
The purpose of range() in Python is as loop control,
No, the purpose of range() is to create a list, as the docs state.

http://docs.python.org/lib/built-in-funcs.html

"""
range(...) - This is a versatile function to create lists containing
arithmetic progressions.
"""

Stefan
Jul 18 '06 #16
Paul Boddie wrote:
Yes, he wants range to return an iterator, just like xrange more or
less does now. Given that xrange objects support __getitem__, unlike a
lot of other iterators (and, of course, generators), adding
__contains__ wouldn't be much of a hardship. Certainly, compared to
other notational conveniences bounced around on the various development
lists, this one would probably provide an order of magnitude
improvement on the usual bang per buck development ratio.
xrange already has __contains__. The problem is, it's implemented by a
highly-inefficient sequential search. Why not modify it to merely
check the bounds and (value - start) % step == 0?

Jul 18 '06 #17
On 2006-07-18, tac-tics <ta*******@gmai l.comwrote:
Grant Edwards wrote:
>for pete's sake use the comparison operator like god intended.

if 0 <= i <= 10000:

I'm assuming you used Python's compound comparison as opposed to the
C-style of and'ing two comparisons together to emphasize the fact it is
god's chosen way of doing this ;-)
Exactly!

--
Grant Edwards grante Yow! HUGH BEAUMONT died
at in 1982!!
visi.com
Jul 18 '06 #18
On 2006-07-18, Marc 'BlackJack' Rintsch <bj****@gmx.net wrote:
In <11************ **********@h48g 2000cwc.googleg roups.com>, tac-tics
wrote:
>Grant Edwards wrote:
>>for pete's sake use the comparison operator like god intended.

if 0 <= i <= 10000:

I'm assuming you used Python's compound comparison as opposed to the
C-style of and'ing two comparisons together to emphasize the fact it is
god's chosen way of doing this ;-)

Pete doesn't like to be called god in public. ;-)
Interesting point. Does the phrase "for pete's sake as god
intended" equate pete with god?

It's possible that pete is not god and yet god's intentions are
in pete's best interest, so something could be "for pete's
sake" and "as god intended" without pete being god.

That said, "for pete's sake" is probably a just an cleaned up
version of "for god's sake", so I probably did call pete god.

--
Grant Edwards grante Yow! This PORCUPINE knows
at his ZIPCODE... And he has
visi.com "VISA"!!
Jul 18 '06 #19
On 2006-07-18, Paul Boddie <pa**@boddie.or g.ukwrote:
John Machin wrote:
>>
range() and xrange() are functions. You are suggesting that 2
*functions* should acquire a __contains__ method each? I trust
not.

Well, range is a function in the current implementation,
although its usage is similar to that one would get if it were
a class, particularly a subclass of list or one providing a
list-style interface. With such a class, you could provide a
__contains__ method which could answer the question of what
the range contains based on the semantics guaranteed by a
range (in contrast to a normal list).
>Perhaps you meant that the acquisitors should be the objects
that those functions return.

The whole point was to avoid expanding the range into a list.
It's unclear what you're referring to as "the range".

Perhaps you're thinking of a slice? Somethign like

if (0:10000).conta ins(x):

--
Grant Edwards grante Yow! Make me look like
at LINDA RONSTADT again!!
visi.com
Jul 18 '06 #20

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

Similar topics

29
7487
by: Chris Dutrow | last post by:
I searched around on the net for a bit, couldn't find anything though. I would like to find some code for a function where I input A Range Of Integers For example: Function( 1, 100 ); And the function will return me an array holding a random subset of integers in that range of a size that I specify So the Function would Probabaly look something like this:
0
1015
by: illo | last post by:
hello guys... a little but very imposrtant question... I have a broadband connection in my office, and i would like to use this connection also from my house (150 meters from the office)... I bought a router and 2 range extenders of belkin.... With the router everything functions very well,
5
5950
by: sameer_deshpande | last post by:
Hi, I need to create a partition table but the column on which I need to create a partition may not have any logical ranges. So while creating or defining partition function I can not use any range. like CREATE PARTITION FUNCTION my_part_func (NUMERIC(7)) AS RANGE LEFT FOR VALUES (1,100,1000);
3
2852
by: toton | last post by:
Hi, I want ro iterate over a few container class within a range specified, instead of begin & end. How to construct a range class, which takes start & end, and iteration is available within that range only. Itaration may be const, bidiractional, forward or backward. Say I have a vector or other container class, like vector<intvec; and want to return a range class like range(vec.begin()+5,
3
4133
by: Alexander Higgins | last post by:
Hello, I would like to thank everyone for there help in advance. I have form which is using an iframe as a Rich Text Editor. Everything works as expected in IE but I have two issues with Firefox. I am using the following to make the frame editable: tmp=document.getElementById("adeditor").contentWindow.document tmp.designMode="On";
2
2214
by: Joe Goldthwaite | last post by:
I've been playing with Python a bit. Doing little performance benchmarks and working with Psyco. It's been fun and I've been learning a lot. For example, in a previous post, I was looking for a way to dynamically add new runtime function to a class. Martin told me to use a class instance variable instead. It turns out that's faster than hard coding a list of functions. Thanks Martin. I read that the range function builds a list and...
10
3021
by: Rafael Cunha de Almeida | last post by:
Hi, I've found several sites on google telling me that I shouldn't use rand() % range+1 and I should, instead, use something like: lowest+int(range*rand()/(RAND_MAX + 1.0))
0
10346
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
10157
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
10096
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
9956
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
6742
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
5386
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...
0
5514
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4055
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
2887
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.