Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash-preview-04-17· GoogleHugging Face LMArena Human Preference 140K

Write a python script that makes a negative strand(so inverted atcg, backwards) out of…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-7-sonnet-20250219’s answer.
  1. User

    Write a python script that makes a negative strand(so inverted atcg, backwards) out of positive DNA strand FASTA sequence file.

  2. Gemini Assistant

    Okay, here is a Python script that reads a FASTA file, calculates the negative strand (reverse complement) of each DNA sequence, and writes the results to a new FASTA file.

    import argparse
    import textwrap
    import sys
    
    def parse_fasta(filepath):
        """
        Parses a FASTA file and yields header and sequence pairs.
        Handles multi-line sequences.
        """
        current_header = None
        current_sequence = []
        try:
            with open(filepath, 'r') as f:
                for line in f:
                    line = line.strip()
                    if not line:  # Skip empty lines
                        continue
                    if line.startswith('>'):
                        if current_header:  # Yield previous sequence if exists
                            yield (current_header, "".join(current_sequence))
                        current_header = line
                        current_sequence = []
                    else:  # Sequence line
                        if current_header is None:
                             # File doesn't start with '>' - invalid FASTA
                            raise ValueError("FASTA file must start with a header ('>')")
                        current_sequence.append(line)
                # Yield the last sequence after the loop
                if current_header:
                    yield (current_header, "".join(current_sequence))
        except FileNotFoundError:
            raise FileNotFoundError(f"Input file not found at {filepath}")
        except Exception as e:
            raise IOError(f"Error reading or parsing FASTA file {filepath}: {e}")
    
    
    def reverse_complement(dna_seq):
        """
        Calculates the reverse complement of a DNA sequence.
        Handles A, T, C, G, N (and lowercase equivalents).
        Raises ValueError for unknown characters.
        """
        complement_map = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C', 'N': 'N',
                          'a': 't', 't': 'a', 'c': 'g', 'g': 'c', 'n': 'n'}
    
        complemented_seq = []
        for base in dna_seq:
            if base in complement_map:
                complemented_seq.append(complement_map[base])
            else:
                # Handle unknown characters - strictly stick to the rules
                raise ValueError(f"Invalid DNA base '{base}' found in sequence.")
    
        # Join and reverse
        # The standard definition of reverse complement is (complement(seq))[::-1]
        # or (seq[::-1]).complement() - the result is the same.
        return "".join(complemented_seq)[::-1]
    
    
    def format_fasta_sequence(sequence, wrap_length=60):
        """
        Wraps a sequence string for FASTA output.
        """
        return textwrap.fill(sequence, width=wrap_length)
    
    
    def main():
        parser = argparse.ArgumentParser(
            description="Generates the negative strand (reverse complement) of DNA sequences from a FASTA file."
        )
        parser.add_argument(
            '-i', '--input',
            required=True,
            help='Input FASTA file path containing DNA sequences.'
        )
        parser.add_argument(
            '-o', '--output',
            required=True,
            help='Output FASTA file path for the negative strand sequences.'
        )
        parser.add_argument(
            '-w', '--wrap',
            type=int,
            default=60,
            help='Wrap sequence lines in the output FASTA at this many characters (default: 60). Set to 0 for no wrapping.'
        )
    
    
        args = parser.parse_args()
    
        try:
            with open(args.output, 'w') as outfile:
                print(f"Processing sequences from '{args.input}'...")
                for header, sequence in parse_fasta(args.input):
                    try:
                        # Calculate reverse complement
                        neg_strand_seq = reverse_complement(sequence)
    
                        # Modify header to indicate it's the negative strand
                        # Append "_negative_strand" to the first word of the header
                        parts = header.split(maxsplit=1)
                        base_header = parts[0] + "_negative_strand"
                        rest_of_header = parts[1] if len(parts) > 1 else ""
                        neg_strand_header = base_header + rest_of_header
    
                        # Format sequence with wrapping if requested
                        wrapped_sequence = format_fasta_sequence(neg_strand_seq, wrap_length=args.wrap) if args.wrap > 0 else neg_strand_seq
    
                        # Write to output file
                        outfile.write(neg_strand_header + '\n')
                        outfile.write(wrapped_sequence + '\n')
    
                    except ValueError as e:
                        print(f"Skipping sequence '{header}' due to invalid base: {e}", file=sys.stderr)
                    except Exception as e:
                        print(f"An unexpected error occurred processing sequence '{header}': {e}", file=sys.stderr)
    
            print(f"Negative strand sequences written to '{args.output}'.")
    
        except FileNotFoundError as e:
            print(f"Error: {e}", file=sys.stderr)
            sys.exit(1)
        except IOError as e:
             print(f"Error: {e}", file=sys.stderr)
             sys.exit(1)
        except Exception as e:
            print(f"An unexpected error occurred: {e}", file=sys.stderr)
            sys.exit(1)
    
    
    if __name__ == "__main__":
        main()
    

    How to Use:

    1. Save: Save the code above as a Python file (e.g., dna_neg_strand.py).

    2. Create Input FASTA: Create a sample input FASTA file (e.g., input.fasta):

      >Seq1 Description of sequence 1
      AGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCT
      NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
      AGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCT
      >Seq2 Another sequence
      cgatcgatcgatcgatcgatcgatcgatcgatcgatcgat
      
    3. Run from Command Line: Open your terminal or command prompt, navigate to the directory where you saved the file, and run the script using the input and output filenames:

      python dna_neg_strand.py -i input.fasta -o output_negative_strand.fasta
      
    4. Check Output: A new file named output_negative_strand.fasta will be created with the negative strands:

      >Seq1_negative_strand Description of sequence 1
      AGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCT
      NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
      AGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCT
      >Seq2_negative_strand Another sequence
      TCGATCGATCGATCGATCGATCGATCGATCGATCGATCGAT
      

    Explanation:

    1. argparse: Handles command-line arguments (-i for input file, -o for output file, -w for wrapping length).
    2. parse_fasta(filepath):
      • This is a generator function that reads the FASTA file line by line.
      • It accumulates sequence lines until it encounters a new header (>) or the end of the file.
      • When a sequence is complete, it yields the header and the joined sequence string as a tuple.
      • Includes basic error handling for missing files or invalid FASTA format (e.g., not starting with >).
    3. reverse_complement(dna_seq):
      • Takes a DNA sequence string as input.
      • Defines a dictionary complement_map for base pairing (A-T, C-G, N-N), including lowercase.
      • Iterates through the input sequence, looking up the complement for each base.
      • Raises a ValueError if any character is not a valid DNA base (A, T, C, G, N, case-insensitive).
      • Joins the complemented bases into a string.
      • Uses string slicing [::-1] to reverse the complemented string.
      • Returns the final reverse complemented sequence.
    4. format_fasta_sequence(sequence, wrap_length):
      • Uses textwrap.fill to wrap the output sequence lines to a specified length, which is standard practice for FASTA format.
    5. main():
      • Sets up the argument parser.
      • Opens the specified output file for writing.
      • Iterates through the sequences yielded by parse_fasta.
      • For each sequence, it calls reverse_complement.
      • It modifies the header by appending _negative_strand to the original header line (specifically, after the first "word" if there's a description, preserving the description).
      • Formats the resulting negative strand sequence using format_fasta_sequence.
      • Writes the modified header and the wrapped sequence to the output file.
      • Includes error handling to catch issues during file processing or sequence processing (like invalid bases). Errors are printed to standard error (sys.stderr).

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.