Skip to content

Instantly share code, notes, and snippets.

@VehpuS
Last active April 21, 2024 11:07
Show Gist options
  • Save VehpuS/3e4592c215184f1980f17c38daba67dc to your computer and use it in GitHub Desktop.
Save VehpuS/3e4592c215184f1980f17c38daba67dc to your computer and use it in GitHub Desktop.
Given a python slice object and a given length, return a range representing the indices that should be returned for that slice for a collection of that length (useful for implementing __getitem__ for slice as index)
def range_from_slice_overcomplicated(slc: slice, length: int) -> range:
step = 1 if slc.step is None else slc.step
assert step != 0, "slice step cannot be zero"
default_start = 0 if step > 0 else length - 1
default_end = length if step > 0 else 0
return range(
default_start if slc.start is None else (length + slc.start) if slc.start < 0 else slc.start,
default_end if slc.stop is None else max(-1, (length + slc.stop)) if slc.stop < 0 else min(slc.stop, length),
step
)
def range_from_slice(
slc: slice, # slice used to generate the range
length: int, # the length of the iterable the slice is applied to
) -> range: # range equivalent of the slice for an iterator of a given length
'''Given a python slice object and a given length, return a range representing the indices that should be returned for that slice for a collection of that length (useful for implementing __getitem__ for slice as index)'''
return range(length)[slc]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment