Search code examples
pythondna-sequence

Tuple to table from counting DNA sequences


I want to count the number of bases in a DNA sequence, return the counts of each type of base in the sequence, and also print out a two column table where the first column is the base and the second column is the associated base count. I can get the function to return the base count but I am not sure how to print the table. I would like to do this analysis with base python functions although I assume it would be easier to do with some python module.

Code:

 def base_counter(DNA):
    A = 0
    T = 0
    G = 0
    C = 0
    for base in DNA:
        if base == "A":
            A = A + 1
        elif base == "T":
            T = T + 1
        elif base == "G":
            G = G + 1
        elif base == "C":
            C = C + 1
        else:
            pass
    return A,T,G,C

Parameter input:

dna="AAGCTACGTGGGTGACTTT"

Function call:

counts=base_counter(dna)
print(counts)

Output:

(4, 6, 6, 3)

Desired output:

print(counts)
  A   4
  T   6
  G   6
  C   3

and

counts
(4, 6, 6, 3)

Solution

  • from within the function:

    out_str="A    "+str(A)+"\n"+\
          "T    "+str(T)+"\n"+\
          "G    "+str(G)+"\n"+\
          "C    "+str(C)
    return out_str
    

    now you can call and print it and it will be printed in your desired format:

    result=base_counter(DNA)
    print(result)
    

    for OP's request full code:

    def base_counter(DNA):
        A = 0
        T = 0
        G = 0
        C = 0
        for base in DNA:
            if base == "A":
                A = A + 1
            elif base == "T":
                T = T + 1
            elif base == "G":
                G = G + 1
            elif base == "C":
                C = C + 1
        out_str = "A    " + str(A) + "\n"+\
        "T    " + str(T) + "\n"+\
        "G    " + str(G) + "\n"+\
        "C    " + str(C)
        return out_str
    
    base=base_counter("AAGCTACGTGGGTGACTTT")
    print(base)
    

    output:

    A    4
    T    6
    G    6
    C    3