2

I am trying to find the most frequent substrings (of a certain lenght L) on a string, but allowing a certain threshold or error T (in amy position of the substrings), obviously not longer than L itself. However, I have not had any success so far. How could I complete the code?

stn='KLHLHLHKPLHLHLPHHKLH'
L = 4 #(lenght of the pattern)
T = 1 #(maximum tolerance or permitted error in any position of the query pattern) 

pattcount = {}
for n in range(len(stn)- L+1):
patt = stn[n:n+L]
s_ = stn[i:i+len(patt)]
if LevenshteinDistance(s_, patt) == T:
pattcount[patt] = pattcount[patt] + 1 if pattcount.has_key(patt) else 1

max = 0
max_patt = []
for p,v in pattcount.iteritems():
if v > max:
max_patt = [p]
max = v
elif v == max:
max_patt += [p]
print (" ".join(max_patt))

Therefore, for example, if the most frequent is KLH, how can the frequencies of HLH, PLH, KLP, KPH inflate the frequencies of KLH (in order to be reported)?

4

1 回答 1

0
>>> from Levenshtein import distance
>>> from collections import defaultdict
>>> tups = [stn[i:i+L] for i in range(0, len(stn) - (L - 1))]
>>> print tups
['KLHL', 'LHLH', 'HLHL', 'LHLH', 'HLHK', 'LHKP', 'HKPL', 'KPLH', 'PLHL', 'LHLH',
 'HLHL', 'LHLP', 'HLPH', 'LPHH', 'PHHK', 'HHKL', 'HKLH']
>>> d = defaultdict(list)
>>> [d[x].append(y) for x in tups for y in tups 
                                  if x is not y and distance(x, y) <= T]
>>> print d
defaultdict(<type 'list'>, {
               'KLHL': ['HLHL', 'PLHL', 'HLHL'], 
               'LHLP': ['LHLH', 'LHLH', 'LHKP', 'LHLH'], 
               'HLHK': ['HLHL', 'HLHL'], 
               'HLHL': ['KLHL', 'HLHK', 'PLHL', 'KLHL', 'HLHK', 'PLHL'], 
               'LHKP': ['LHLP'], 
               'LHLH': ['LHLP', 'LHLP', 'LHLP'], 
               'PLHL': ['KLHL', 'HLHL', 'HLHL']})
>>> s = sorted(d.iterkeys(), key=lambda k: len(d[k]), reverse=True)
>>> print s
['HLHL', 'LHLP', 'KLHL', 'LHLH', 'PLHL', 'HLHK', 'LHKP']
于 2013-11-15T04:02:23.910 回答