The code snippet below will populate the store
dictionary keyed by the nucleotide patterns and values as lists that contain the occupancy for each index. (Updated answer now includes arbitrary length nucleotide counts)::
from itertools import count
def pattern_update(sequence, width=2, store={}):
"""
Accumulates nucleotide patterns of a certain width with
position counts at each index.
"""
size = len(sequence) + 1
def zeroes():
"Generates an empty array that holds the positions"
return [ 0 ] * (size - width)
ends = range(width, size)
for lo, hi in zip(count(), ends):
key = sequence[lo:hi]
store.setdefault(key, zeroes())[lo] += 1
return store
The code at multipatt.py demonstrates its use in a full program. Set the size
to the maximal possible sequence size. A typical use case::
store = {}
seq1 = 'ATGCT'
pattern_update(seq1, width=2, store=store)
seq2 = 'ATCGC'
pattern_update(seq2, width=2, store=store)
print store
will print::
{'CG': [0, 0, 1, 0], 'GC': [0, 0, 1, 1], 'AT': [2, 0, 0, 0],
'TG': [0, 1, 0, 0], 'TC': [0, 1, 0, 0], 'CT': [0, 0, 0, 1]}