Skip to content
Snippets Groups Projects
Commit 608a9f1d authored by Wout De Nolf's avatar Wout De Nolf
Browse files

utility method to inverse a slice

parent d0e5e78c
No related branches found
No related tags found
1 merge request!182Draft: Resolve "Utility method to inverse a slice object"
Pipeline #225167 failed
def reverse_slice(in_slice: slice) -> slice:
"""
Returns a new slice object that reverses the given slice.
Ensures that `data[in_slice][::-1] == data[reverse_slice(in_slice)]`.
:param in_slice: A slice object.
:return: A reversed slice object.
"""
start, stop, step = in_slice.start, in_slice.stop, in_slice.step
if step is None:
step = 1
if step > 0:
start_inv = stop - step if stop is not None else None
stop_inv = start - step if start is not None else None
else:
start_inv = stop + step if stop is not None else None
stop_inv = start + step if start is not None else None
step_inv = -step
return slice(start_inv, stop_inv, step_inv)
from numpy.random import RandomState
from est.core.utils.slicing import reverse_slice
def test_reverse_slice():
rng = RandomState(42)
data = list(range(100))
for _ in range(1000):
start = rng.choice([None] * 20 + list(range(-150, 150)))
stop = rng.choice([None] * 20 + list(range(-150, 150)))
step = rng.choice([-10, -5, -3, -2, -1, 1, 2, 3, 5, 10, None])
in_slice = slice(start, stop, step)
rev_slice = reverse_slice(in_slice)
expected = data[in_slice][::-1]
actual = data[rev_slice]
assert expected == actual, f"Failed for slice({start}, {stop}, {step})"
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment