Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

DNA comp. quetion

So for this question, it asks us to get the complementary DNA structure for the test cases

so A it would be T T would be A ext.

So I really don't understand the code behind it .join[complement[x]for x in DNA]

I was wondering why you put the [x] there and why does it know that x is the value pair in the key-value pair

The Code

   def DNA_strand(DNA):
      pairs = {"A":"T", "T":"A", "C":"G", "G":"C"}
      return ''.join([pairs[x] for x in DNA])

if someone could explain this in detail it would be great! :) especially why you put the x in brackets and how it knows its the value part in the key-value pair.

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

Drilling down it could be read as:

    # define translation of DNA chars
    # <DNA char> : <pairing char>
    pairs = {"A":"T", "T":"A", "C":"G", "G":"C"}
    # build return string
    return <object>
    # object
    # create string form some_list
    ''.join(<some_list>)
    # some_list created using list comprehension 
    [<new_object> based on <iterable>]
    # iterable
    # for each character in the argument DNA
    for x in DNA
    # new_object
    # create object by looking up DNA char in ‘pair’ dict to get matching value.
    # T becomes A,...
    pairs[x]

So for each letter in DNA, creat a list of the matching values in pairs, join this list of characters into a string, return this string.

So, x is the DNA character, and pairs[x] is the look up of its corresponding value.

Post back if you need more help. Good luck!!!

Thanks man !

But quick question how does it know to get the correlating value in the dictionary.

Chris Freeman
Chris Freeman
Treehouse Moderator 68,441 Points

The code pairs[x] is a lookup in the pairs dict using “x” as the key. This returns the corresponding value.

So if the parameter DNA was the string “AC”, in the first loop of the list comprehension x would be set to “A”. The lookup would be pairs[“A”] which returns the value “T”. The second loop the lookup would be pairs[“C”] which returns “G”.

The join would convert [“T”, “G”] into “TG”.