|
5 | 5 | own faster implementation. |
6 | 6 | """ |
7 | 7 |
|
8 | | -from .baseline import find_matches as _baseline |
| 8 | +from __future__ import annotations |
9 | 9 |
|
10 | 10 |
|
11 | 11 | def find_matches(fasta_path: str, pattern: bytes) -> list[tuple[str, list[int]]]: |
12 | 12 | """Find every FASTA record whose sequence contains ``pattern``. |
13 | 13 |
|
14 | 14 | Returns ``[(record_id, [positions...]), ...]`` in file order. |
15 | 15 | """ |
16 | | - # TODO: remove this delegation and write your own implementation here. |
17 | | - return _baseline(fasta_path, pattern) |
| 16 | + # Read as bytes — skips the text-decode cost the baseline pays. |
| 17 | + with open(fasta_path, "rb") as f: |
| 18 | + data = f.read() |
| 19 | + |
| 20 | + plen = len(pattern) |
| 21 | + _find = bytes.find # local lookup |
| 22 | + matches: list[tuple[str, list[int]]] = [] |
| 23 | + |
| 24 | + # Skip the first (empty) chunk before the first ">". |
| 25 | + for record in data.split(b">")[1:]: |
| 26 | + # Header ends at the first newline. |
| 27 | + nl = record.index(b"\n") |
| 28 | + # Build the contiguous sequence by stripping newlines — a single |
| 29 | + # C-level bytes.replace() call instead of split-then-join. |
| 30 | + sequence = record[nl + 1 :].replace(b"\n", b"") |
| 31 | + |
| 32 | + # Quick exit: most records do not contain the pattern at all. |
| 33 | + # ``in`` delegates to a fast C memchr/memmem scan. |
| 34 | + pos = _find(sequence, pattern) |
| 35 | + if pos == -1: |
| 36 | + continue |
| 37 | + |
| 38 | + record_id = record[:nl].strip().decode("ascii") |
| 39 | + |
| 40 | + # Collect all (overlapping) hit positions. |
| 41 | + positions: list[int] = [pos] |
| 42 | + start = pos + 1 |
| 43 | + while True: |
| 44 | + pos = _find(sequence, pattern, start) |
| 45 | + if pos == -1: |
| 46 | + break |
| 47 | + positions.append(pos) |
| 48 | + start = pos + 1 |
| 49 | + |
| 50 | + matches.append((record_id, positions)) |
| 51 | + |
| 52 | + return matches |
0 commit comments