range() is not the best way to check range?
Nick Craig-Wood
nick at craig-wood.com
Tue Jul 18 04:30:04 EDT 2006
Grant Edwards <grante at visi.com> wrote:
> Creating and then searching a 10,000 element list to see if a
> number is between two other numbers is insane.
> Using xrange as somebody else suggested is also insane.
Aye to both
> If you want to know if a number is between two other numders,
> for pete's sake use the comparison operator like god intended.
>
> if 0 <= i <= 10000:
Sets are pretty fast too, and have the advantage of flexibility in
that you can put any numbers in you like
$ python2.4 -m timeit -s 's=range(0,10000); i=5000' 'i in s'
1000 loops, best of 3: 228 usec per loop
$ python2.4 -m timeit -s 's=set(range(0,10000)); i=5000' 'i in s'
1000000 loops, best of 3: 0.312 usec per loop
$ python2.4 -m timeit -s 'i=5000' '0 <= i < 10000'
1000000 loops, best of 3: 0.289 usec per loop
The below prints
range) That took 21.512 seconds: result 10001.0
set) That took 0.023 seconds: result 10001.0
comparison) That took 0.024 seconds: result 10001.0
............................................................
import time
start = time.time()
a = 1.0
for i in range(0, 30000):
if i in range(0, 10000):
a += 1
dt = time.time() - start
print "range) That took %.3f seconds: result %s" % (dt, a)
start = time.time()
a = 1.0
mine = set(range(0, 10000))
for i in range(0, 30000):
if i in mine:
a += 1
dt = time.time() - start
print "set) That took %.3f seconds: result %s" % (dt, a)
start = time.time()
a = 1.0
mine = set(range(0, 10000))
for i in range(0, 30000):
if 0 <= i < 10000:
a += 1
dt = time.time() - start
print "comparison) That took %.3f seconds: result %s" % (dt, a)
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list