Langfao Langfao - 1 year ago 45
Python Question

Defining a function that counts 2 letters and divides that by total length of the word

I'm trying to create a code that counts how many G's and C's there are in a "strand of DNA" and calculate the percentage of the G's + C's in that strand, e.g.


There are 18 letters in that string and 8 G's + C's together.

I am struggling so far to even count the letter of G's in a strand in my code, this is what I have so far:

def gcContent(dnaMolecule):
count = 0
for g in dnaMolecule:
count += 1
return count

and when I type it into the interactive python shell the result is this:

In [1]: gcContent('a')
Out[1]: 1.0

It's not counting the amount of G's so far and it says one no matter what if I type in 1 character inside the brackets after

Answer Source

You can use the count method that every string has.

def gcContent(dnaMolecule):
    dnaMolecule = dnaMolecule.lower()
    count = dnaMolecule.count('g') + dnaMolecule.count('c')
    return count / len(dnaMolecule)