How do I compute the number of elements that would result from a call to range(start, stop, step) before I actually call it.
The context is that I’m implementing slice indexing into an object
def __init__(self, impl_object):
self.impl=impl_object # the object that actually holds (or generates) an array of values
def __getitem__(self, key):
if isinstance(key, slice):
(start,stop,step)=key.indices( self.impl.numValues() )
# It would be nice to know how many items I'm dealing with
# here
...snip...
I’ve convinced myself that for step>0
len(range(start,stop,step))==(start-stop+step-1)/step
but I don’t see how to generalize this for negative steps.
Edit: I require (strongly prefer) that the solution take O(1) time.
The easiest way is
xrange.__len__calculates the number of elements it wouldyield, without constructing the range in memory.