2

This is the code I have to achieve my objective as stated in the title. The problem I seem to have right now is the second line of code. The moment I added it the program stopped working without giving me an error. Thanks in advance for the help.

seqDNA = input()
seqDNA = seqDNA.upper()
comp = ''
for c in seqDNA:
    if c == 'a':
        comp = comp + 'u'
    elif c == 't':
        comp = comp + 'a'
    elif c == 'g':
        comp = comp + 'c'
    elif c == 'c':
        comp = comp + 'g'
print(comp)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
forsale
  • 21
  • 1

1 Answers1

0

This is the correct behavior since you check uppercase characters against lowercase ones.

After seqDNA = seqDNA.upper(), your string contains uppercase characters. For instance:

seqDNA = 'UGCGGCGAATATTT'

If we now iterate through it with for c in seqDNA, c will contain an uppercase character (i.e. 'C'). Now if you compare c == 'C', you compare 'c' == 'C', and those are not equal.

So you should modify the tests to:

seqDNA = input()
seqDNA = seqDNA.upper()
comp = ''
for c in seqDNA:
    if c == 'A':
        comp = comp + 'u'
    elif c == 'T':
        comp = comp + 'a'
    elif c == 'G':
        comp = comp + 'c'
    elif c == 'C':
        comp = comp + 'g'
print(comp)

That being said, your code works inefficient: first of all the sequence of elif statements is expensive, and furthermore you perform a comp = comp + 'u' operation. String appending runs in O(n), making this algorithm O(2).

We can improve it by using a dictionary, and **use ''.join(..) over appending manually.

seqDNA = input()
seqDNA = seqDNA.upper()
trans = {
    'A': 'u',
    'T': 'a',
    'G': 'c',
    'C': 'g'
}
comp = ''.join(trans[c] for c in seqDNA)
print(comp)

This will raise a KeyError in case the seqDNA contains a character, other than 'A', 'T', 'G', and 'C'. Which seems to me as reasonable behavior. In case you simply want to ignore these characters, you can use .get(..,'') over [c]:

seqDNA = input()
seqDNA = seqDNA.upper()
trans = {
    'A': 'u',
    'T': 'a',
    'G': 'c',
    'C': 'g'
}
comp = ''.join(trans.get(c,'') for c in seqDNA)
print(comp)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • 1
    I understand and thank you for the code optimization altough I'm not yet comfortable with dictionaries. What I should have done was , and I don't know I didn't remember, was to simply upper in the end: comp = comp.upper() – forsale Oct 16 '17 at 15:49