Reputation: 25
How can I get the complementary reverse for dna? following formula works for first string but when I add the second string in the list it does not work.
dna = ['CAG', 'AGT']
def reverse_complementary (char):
my_dictionary = {"A": "T", "C": "G", "G": "C", "T": "A"}
return "".join([my_dictionary[i] for i in reversed(char)])
print("reverse_complementary =" , reverse_complementary(dna))
Upvotes: 1
Views: 114
Reputation: 13576
If you pass a str
to reverse_complementary
, it will reverse and
translate the characters, which is what you want.
If you pass a list
of str
objects, as you’re doing here, it will
reverse the list
, then try to look up each str
in the dict
, and
that will fail.
How to fix it? That depends on whether you want to pass single DNA sequences or lists of them. The former seems more generic, so I’ll go with that.
reverse_complementary
already works with strings, so that’s unchanged.
We need to call it differently:
dna = ['CAG', 'AGT']
for s in dna:
print("reverse_complementary =" , reverse_complementary(s))
Edit: how to print results as a list.
With a loop:
lst = []
for s in dna:
lst.append(reverse_complementary(s))
print("reverse_complementary =" , lst)
With a list comprehension:
lst = [reverse_complementary(s) for s in dna]
print("reverse_complementary =" , lst)
Upvotes: 2
Reputation: 152677
You need to perform the translation on each of your strings seperatly (and not the list itself), this can be done with a loop or with map
or an explicit list-comprehension, for example:
def reverse_complementary(char):
my_dictionary = {"A": "T", "C": "G", "G": "C", "T": "A"}
return ["".join([my_dictionary[i] for i in reversed(seq)]) for seq in char]
However when you want to map characters to other characters it's generally better to use str.maketrans
and str.translate
:
to_complement = str.maketrans({"A": "T", "C": "G", "G": "C", "T": "A"})
def reverse_complementary(char):
return [seq[::-1].translate(to_complement) for seq in char]
The [::-1]
is another (also more efficient) way of reversing a string.
Upvotes: 0