0

I am currently trying to complete a project where I have to use a dictionary to find the complement of a strand of DNA. The string imported from my .txt file is composed entirely of the letters ACTG. To find the complement I need to switch every A and T as well as every C and G. However, when I try to accomplish this with the dictionary it will switch all the letters to only As or only Gs if that makes sense. I need to find a way to make it iterate through the string one letter at a time and replace them in that way. I'll insert the code I have so far, please help!

#open file with DNA strand
df = open("dnafile.txt", 'r')

#function for finding the complementary strand
def encode(code,DNA):
    for k in code:
        DNA = DNA.replace(k,code[k])
    print('The complementary strand is: ' + DNA)

#carry out this function
code = {'A':'T', 'T':'A', 'C':'G', 'G':'C'}
DNA = df.read()
encode(code,DNA)
  • 2
    Your code is fine but think about the logic here. Once it switches all the As to a T, then the dictionary tells it to switch the T to an A. You would need to save the A value to a temporary value or else all As and Ts will end up as an A – A.Kot Oct 24 '16 at 17:26

1 Answers1

1

You can use a list comprehension and the joinmethod of strings:

DNA = ''.join(code[k] for k in DNA)
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96