|
5 | 5 | own faster implementation. |
6 | 6 | """ |
7 | 7 |
|
8 | | -from .baseline import find_matches as _baseline |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +def _find_positions(sequence: bytes, pattern: bytes) -> list[int]: |
| 11 | + positions = [] |
| 12 | + start = 0 |
| 13 | + find = sequence.find |
| 14 | + |
| 15 | + while True: |
| 16 | + pos = find(pattern, start) |
| 17 | + |
| 18 | + if pos == -1: |
| 19 | + break |
| 20 | + |
| 21 | + positions.append(pos) |
| 22 | + start = pos + 1 |
| 23 | + |
| 24 | + return positions |
9 | 25 |
|
10 | 26 |
|
11 | 27 | def find_matches(fasta_path: str, pattern: bytes) -> list[tuple[str, list[int]]]: |
12 | 28 | """Find every FASTA record whose sequence contains ``pattern``. |
13 | 29 |
|
14 | 30 | Returns ``[(record_id, [positions...]), ...]`` in file order. |
15 | 31 | """ |
16 | | - # TODO: remove this delegation and write your own implementation here. |
17 | | - return _baseline(fasta_path, pattern) |
| 32 | + matches: list[tuple[str, list[int]]] = [] |
| 33 | + |
| 34 | + with open(fasta_path, "rb") as f: |
| 35 | + record_id = None |
| 36 | + seq_parts = [] |
| 37 | + |
| 38 | + for line in f: |
| 39 | + |
| 40 | + if line.startswith(b">"): |
| 41 | + |
| 42 | + # process previous record |
| 43 | + if record_id is not None: |
| 44 | + sequence = b"".join(seq_parts) |
| 45 | + |
| 46 | + positions = _find_positions(sequence, pattern) |
| 47 | + |
| 48 | + if positions: |
| 49 | + matches.append((record_id, positions)) |
| 50 | + |
| 51 | + # begin new FASTA record |
| 52 | + record_id = line[1:].strip().decode("ascii") |
| 53 | + seq_parts = [] |
| 54 | + |
| 55 | + else: |
| 56 | + seq_parts.append(line.strip()) |
| 57 | + |
| 58 | + # process final record |
| 59 | + if record_id is not None: |
| 60 | + sequence = b"".join(seq_parts) |
| 61 | + |
| 62 | + positions = _find_positions(sequence, pattern) |
| 63 | + |
| 64 | + if positions: |
| 65 | + matches.append((record_id, positions)) |
| 66 | + |
| 67 | + return matches |
0 commit comments