Hi Guys, 
I am new to the forum to come directly with a question / problem.

I want to write a program that counts the patterns like this.
I have given such sequences as an example:

> - A: AAAAAAAAA
- B: AAAAACAAG
- C: GAAAACGAA
- D: AAAAAAAAT
> 

A patten is a group of four letters of the four groups. As an example, the first Patten would be "AAGA". Now I wonder how many times that happens in my entire Sequenze. So far I have only found programs that are looking for a given pattern. Does anyone have an idea how to program this or do you already know where this was done?

I'm very thankful for your help!

Best regards




You could use a [Python regular expression][1] with a [lookahead][2] for your [kmer][3] of interest:

    >>> import re
    >>> a = 'AAAAACAAGAAA'
    >>> [x.start() for x in re.finditer('(?=AAA)', a)]
    [0, 1, 2, 9]
    >>> [x.start() for x in re.finditer('(?=AAZ)', a)]
    []

The `len()` property of the list of "hit" start positions is the number or frequency of the kmer in question.

Consider also what you might need to do in Python, if you need to search the [reverse complement][4] of the query sequence.

Another possible approach would be to write a [Python generator][5] of all contiguous substrings of a query sequence (and, possibly, its reverse complement). Using a [generator][6] would reduce the memory overhead of making a list from all substrings. 

One can iterate or walk through the output of a generator, one element at a time. You might compare the generator output with your kmer of interest and increment a counter, if there's a match.


  [1]: https://docs.python.org/2/library/re.html
  [2]: https://www.regular-expressions.info/lookaround.html
  [3]: https://en.wikipedia.org/wiki/K-mer
  [4]: https://bioinformatics.stackexchange.com/a/3595/776
  [5]: https://stackoverflow.com/a/22470158/19410
  [6]: https://medium.freecodecamp.org/how-and-why-you-should-use-python-generators-f6fb56650888