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

Simon Forman rogue_pedro at yahoo.com
Tue Jul 18 13:33:23 EDT 2006


Diez B. Roggisch wrote:
> Simon Forman wrote:
>
> > Nick Craig-Wood wrote:
> >>
> >> Sets are pretty fast too, and have the advantage of flexibility in
> >> that you can put any numbers in you like
> >>
> >
> > I know this is self-evident to most of the people reading this, but I
> > thought it worth pointing out that this is a great way to test
> > membership in range(lo, hi, step) without doing "the necessary
> > algebra".
> >
> > i.e.  n in set(xrange(0, 10000, 23)) ...
>
> No, its not. It works, but it works by no means faster than
>
> n in range(0, 10000, 23)
>
> Both need O(n), which is a bit slow compared to
>
> (((n - 15) % 23) == 0 and n >= 15 and n < 10000)
>
> that will run in O(1)
>
> Diez

You're right, of course.  I should have said that if you're testing
such a membership, say, 30000 times AND you (like me) are slightly
rusty on the algebra and prefer to let the computer do it, then you
could use something like:

test_set = set(xrange(0, 10000, 23))

if n in test_set:
    ...

;-)
~Simon




More information about the Python-list mailing list