from pathlib import Pathfrom typing import List, Tuple, Generator, Mappingdef join_sequences(sequences: List[str]) -> str: """ Joins a list of sequences into a single string by removing leading and trailing whitespace. Args: sequences (List[str]): A list of sequences as strings. Returns: str: The concatenated string of sequences with leading and trailing whitespace removed. """ return "".join(map(lambda x: x.strip(), sequences))def partition(fasta: List[str]) -> Generator[Tuple[str, str], None, None]: """ Partitions a FASTA file into sequence ID and corresponding sequence pairs. Args: fasta (List[str]): A list of lines from a FASTA file. Yields: Tuple[str, str]: A tuple containing sequence ID and its corresponding sequence. Examples: >>> fasta = [ ... ">seq1", ... "ATCG", ... "ATC", ... ">seq2", ... "GTCA", ... "GTC", ... ] >>> for sequence_id, sequence in partition(fasta): ... print(sequence_id, sequence) seq1 ATCGATC seq2 GTCAGTC """ index, sequence_id = 0, "" for i, line in enumerate(fasta): if line.startswith(">"): if i == 0: sequence_id = line.strip().lstrip(">") continue else: yield (sequence_id, join_sequences(fasta[index + 1:i])) index, sequence_id = i, line.strip().lstrip(">") elif (i + 1) == len(fasta): yield (sequence_id, join_sequences(fasta[index + 1:])) else: continuedef read_fasta(path: Path) -> Mapping[str, str]: """ Reads a FASTA file and returns a dictionary of sequence IDs and their corresponding sequences. Args: path (Path): The path to the FASTA file. Returns: Mapping[str, str]: A dictionary mapping sequence IDs to their sequences. Examples: >>> path = Path("sequences.fasta") >>> sequences = read_fasta(path) >>> print(sequences) {"seq1": "ATCGATC", "seq2": "GTCAGTC"} """ with path.open(mode="r") as f: sequences = partition(f.readlines()) return dict(sequences)
Solution #1
def gc_content(sequence): g, c = sequence.count("G"), sequence.count("C") return (g + c) / len(sequence)def highest_gc_content(sequences): sequence_header = "" highest_gc = 0 for header, sequence in sequences.items(): gc = gc_content(sequence) if gc > highest_gc: highest_gc = gc sequence_header = header return sequence_header, highest_gc