John Lekberg


JUNTO Practice - "Rosalind, Complementing a Strand of DNA"

Discussed on 2018-09-04.

Rosalind, Complementing a Strand of DNA


Solution - John

#!/usr/bin/env python3
#
# Read a string of DNA from standard input and output
# its reverse complement on standard output.
#

import sys

# Guanine, Adenine, Cytosine, Thymine.
#
bases = {"G", "A", "T", "C"}

# Complements of above bases.
#
complement_table = {"G": "C", "A": "T", "T": "A", "C": "G"}

# Function that applies `complement_table` to complement a base.
# Ex. complement('G') == 'C'
#
complement = complement_table.get

# Read string of characters from standard input and only keep characters
# corresponding to one of the bases.
#
dna_string = list(filter(lambda c: c in bases, sys.stdin.read()))

# Reverse and then complement `dna_string`.
#
rc_string = map(complement, reversed(dna_string))

# Print the result to standard output as a string.
#
print("".join(rc_string))

Solution - Oscar

def reverse_complement(s):
    original = "ATCG"
    complement = "TAGC"
    nucl_compl = "".maketrans(original, complement)
    return "".join(reversed(s)).translate(nucl_compl)


print(reverse_complement(reverse_complement("ATCGATTCAAATTT")))