1
\$\begingroup\$

I want to calculate the distance between k-mers instances in a long sequence (words of length k, bigrams, trigrams, etc. In bioinformatics the are called k-mers). I developed this code that look for starts of the k-mers and then calculate the distance between the starts. I am not sure I am doing it right:

from itertools import pairwise

seq = "ACCGGCTTTAACGGCCTACGCGTTTTAAGCCGG"
di = "CG"

def get_inter_kmer_distance(seq, kmer):
    lk = len(kmer)
    starts = []
    for i, _ in enumerate(seq):
        di = seq[i:i+lk]
        if di == kmer:
            starts.append(i)
    #print(list(pairwise(starts)))
    dist = [j - i for i, j in pairwise(starts)]
    return dist, starts

get_inter_kmer_distance(seq, di)
([9, 7, 2, 10], [2, 11, 18, 20, 30])

get_inter_kmer_distance(seq, "AC")
([10, 7], [0, 10, 17])

I really have doubts if I have do overlaps or just plain divide the sequence in the kmers (like, "AC CG GC TT TA AC GG CC TA CG CG TT TT AA GC CG G"). Any suggestion to correct or improve the code would be appreciated.

Thank you for your time.

Paulo

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$
di = "CG"

Consider renaming this to dimer.


        di = seq[i : i + lk]

This appears to be an ill-chosen identifier. It only makes sense in the case that lk is 2.


    for i, _ in enumerate(seq):

This is fine, but the usual idiom would be

    for i in range(len(seq)):

have doubts if I have do overlaps or

Not to worry. You are correctly examining each k-mer.

If OTOH you had coded

    for i in range(0, len(seq), 2):

that would wind up incorrectly ignoring half the dimers.

\$\endgroup\$
1
  • \$\begingroup\$ Thank you. At the beginning I would try only dimers, but I decided to use for other k-mers lenghts. 8) \$\endgroup\$ Jul 6, 2023 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.