Skip to content

Commit

Permalink
Bugfix for range subsetting when 'indices' is also a range.
Browse files Browse the repository at this point in the history
If 'indices' has a negative 'stop', the previous conversion of 'indices' to
slice would translate the negative stop to a reverse index (i.e., the last
element) rather than its actual interpretation as 'one before the start'. This
is wrong when trying to reach the first element for a negative 'step'.
  • Loading branch information
LTLA committed Dec 17, 2024
1 parent e2c1c7f commit 6b94d54
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/biocutils/subset_sequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ def _subset_sequence_list(x: list, indices: Sequence) -> list:
@subset_sequence.register
def _subset_sequence_range(x: range, indices: Sequence) -> Union[list, range]:
if isinstance(indices, range):
return x[slice(indices.start, indices.stop, indices.step)]
return range(
x.start + x.step * indices.start,
x.start + x.step * indices.stop,
x.step * indices.step
)
else:
return [x[i] for i in indices]
11 changes: 11 additions & 0 deletions tests/test_subset_sequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,14 @@ def test_subset_range():
x = range(10, 20)
assert subset_sequence(x, range(2, 8, 2)) == range(12, 18, 2)
assert subset_sequence(x, [0, 1, 5, 9]) == [10, 11, 15, 19]
assert subset_sequence(x, range(9, -1, -1)) == range(19, 9, -1)

x = range(10, 30, 3)
assert subset_sequence(x, range(2, 7, 2)) == x[2:7:2]
assert subset_sequence(x, range(5, 0, -2)) == x[5:0:-2]
assert subset_sequence(x, range(len(x) - 1, -1, -1)) == x[::-1]

x = range(100, 21, -6)
assert subset_sequence(x, range(3, 10, 2)) == x[3:10:2]
assert subset_sequence(x, range(7, 1, -1)) == x[7:1:-1]
assert subset_sequence(x, range(len(x) - 1, -1, -1)) == x[::-1]

0 comments on commit 6b94d54

Please sign in to comment.