Python: How would I write a function that takes a string representing a DNA sequence, and return a string representing the complement ('A' and 'T' are complements of each other, as are 'C' and 'G'). The hints given were to use a dictionary to map a symbol A to its complement T, and to use join() rather than string addition.
def dna_complement(text: str) -> str:
assert(dna_complement('AAAACCCGGT') == 'ACCGGGTTTT')
assert dna_complement('AcgTTTcAgCCC') == 'GGGCTGAAACGT'
Solution:-
Here is the Python code for the given requirement. Comments have been added in the code for better explanation.
def dna_complement(text):
# Creating a dictionary mapping the symbols with its complement
dic = {'A':'T','T':'A','C':'G','G':'C'}
# define an empty list
ls = []
# for each character in the input string
for i in range(len(text)):
# if the upper case of the character is a key in a dictionary
if text[i].upper() in dic.keys():
# append the value of that key to the list
ls.append(dic.get(text[i].upper()))
# list ls will contain a list with all characters complement.
# we use the join function to createa string from that list.
# and then use the slicing shortcut [::-1] to reverse that string and return it.
return((''.join(ls))[::-1])
if __name__ == '__main__':
print('The complement of DNA string AAAACCCGGT is ',dna_complement("AAAACCCGGT"))
print('The complement of DNA string AcgTTTcAgCCC is ',dna_complement("AcgTTTcAgCCC"))
The output is as follows:
Get Answers For Free
Most questions answered within 1 hours.