Testing if an index is in a slice

Bryan Olson fakeaddress at nowhere.org
Sun Jan 4 19:03:01 EST 2009


Steven D'Aprano wrote:
> Here's a less verbose version which passes your test cases:
> 
> def inslice(index, slc, len):
>     """Return True if index would be part of slice slc of a 
>     sequence of length len, otherwise return False.
>     """
>     start, stop, stride = slc.indices(len)
>     if stride < 0:
>         return (start >= index > stop) and ((start-index) % -stride == 0)
>     else:
>         return (start <= index < stop) and ((index-start) % stride == 0)
> 
> 
> (Hint: help(slice) is your friend.)

I should really think about abandoning my strategy of doing everything 
the hard way.


-- 
--Bryan




More information about the Python-list mailing list