Skip to content

Commit

Permalink
Re-use existing mapping in normalize_subscript if names are Names.
Browse files Browse the repository at this point in the history
This avoids having to generate a redundant positional index. It will
modify any Names by reference, but I suppose that's fine, as the
reverse mapping inside Names is transparent to the user anyway.
  • Loading branch information
LTLA committed Nov 13, 2023
1 parent da2e252 commit ffd2093
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
13 changes: 10 additions & 3 deletions src/biocutils/normalize_subscript.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from typing import Optional, Sequence, Tuple, Union
import numpy

from .Names import Names


def _raise_int(idx: int, length):
raise IndexError("subscript (" + str(idx) + ") out of range for vector-like object of length " + str(length))
Expand Down Expand Up @@ -119,11 +121,16 @@ def normalize_subscript(
output = []
has_strings = set()
string_positions = []
are_names_indexed = isinstance(names, Names)

for i, x in enumerate(sub):
if isinstance(x, str):
has_strings.add(x)
string_positions.append(len(output))
output.append(None)
if are_names_indexed:
output.append(names.map(x))
else:
has_strings.add(x)
string_positions.append(len(output))
output.append(None)
elif _is_scalar_bool(x):
if x:
output.append(i)
Expand Down
6 changes: 5 additions & 1 deletion tests/test_normalize_subscript.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from biocutils import normalize_subscript
from biocutils import normalize_subscript, Names
import pytest
import numpy

Expand Down Expand Up @@ -95,6 +95,10 @@ def test_normalize_subscript_chaos():
[1, 1, 3, 2, 5, 3, 0],
False,
)
assert normalize_subscript(["B", 1, "D", 2, "F", 3, "A"], 6, Names(names)) == (
[1, 1, 3, 2, 5, 3, 0],
False,
)
assert normalize_subscript(
["B", 1, "A", 2, "B", 3, "A"], 6, ["A", "B", "A", "B", "A", "B"]
) == (
Expand Down

0 comments on commit ffd2093

Please sign in to comment.