Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting multiple letter groups in a string

I've been trying to adapt my python function to count groups of letters instead of single letters and I'm having a bit of trouble. Here's the code I have to count individual letters:

my_seq = "CTAAAGTCAACCTTCGGTTGACCTTGAAAGGGCCTTGGGAACCTTCGGTTGACCTTGAGGGTTCCCTAAGGGTT"

def count_letters(str):
    counts = {}
    for c in str:
        if c in counts:
            counts[c]+=1
        else:
            counts[c]=1
    return counts

counts = count_letters(my_seq)
print(counts)

The function currently spits out counts for each individual letter. Right now it prints this:

{'C': 23, 'T': 30, 'G': 30, 'A': 20}

Ideally, I'd like it to print something like this:

{'CTA': 2, 'TAG': 3, 'CGC': 1, 'GAG': 2 ... }

I'm very new to python and this is proving to be difficult.

like image 903
jarch Avatar asked Aug 10 '26 17:08

jarch


1 Answers

This can be done pretty quickly using collections.Counter.

from collections import Counter

s = "CTAACAAC"

def chunk_string(s, n):
    return [s[i:i+n] for i in range(len(s)-n+1)]

counter = Counter(chunk_string(s, 3))
# Counter({'AAC': 2, 'ACA': 1, 'CAA': 1, 'CTA': 1, 'TAA': 1})

Edit: To elaborate on chunk_string:

It takes a string s and a chunk size n as arguments. Each s[i:i+n] is a slice of the string that is n characters long. The loop iterates over the valid indices where the string can be sliced (0 to len(s)-n). All of these slices are then grouped in a list comprehension. An equivalent method is:

def chunk_string(s, n):
    chunks = []
    last_index = len(s) - n
    for i in range(0, last_index + 1):
        chunks.append(s[i:i+n])
    return chunks
like image 84
Jared Goguen Avatar answered Aug 13 '26 07:08

Jared Goguen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!