Counting all permutations of a substring

mensanator at aol.com mensanator at aol.com
Wed Apr 5 17:47:46 EDT 2006


mensanator at aol.com wrote:
> Chris Lasher wrote:
> > Hi all,
> > How can one count all the permutations of a substring in a string? For
> > a more concrete example, let's say
> > targetstr = 'AAA'
> > and
> > probestr = 'AA'
> >
> > I want to consider how many times one can count probestr ('AA') in
> > targetstr ('AAA'). The value in this example is, obviously, 2: you can
> > match the first and second A's as 'AA' and also the second and third
> > A's as 'AA'. Compiling a regular expression of the probestr and doing a
> > findall(targetstr) will not work because the RE stops on the first
> > combination of 'AA' that it finds (the first and second A's of the
> > targetstr). The regular expression re.compile(r'A{2,}'} will not work,
> > either; it simply consumes all three A's as one match. The string
> > method count('AA') acts similarly to the findall of the 'AA' RE,
> > returning 1, as it only matches the first and second A's.
> >
> > Any suggestions on how to get at that 2nd pair of A's and count it?
> > Humbly, I'm a bit stumped. Any help would be appreciated.
>
> >>> def ss(a,b):
> 	matches = 0
> 	lc = len(a)-len(b)+1
> 	for i in xrange(lc):
> 		if a[i:i+lb]==b:

Oops, should be
 		if a[i:i+len(b)]==b:

> 			print a
> 			print ' '*i+b
> 			print
> 			matches += 1
> 	return matches
>
> >>> ss('AAABCDEAAAAABSAABAWA','AA')
> AAABCDEAAAAABSAABAWA
> AA
>
> AAABCDEAAAAABSAABAWA
>  AA
>
> AAABCDEAAAAABSAABAWA
>        AA
>
> AAABCDEAAAAABSAABAWA
>         AA
>
> AAABCDEAAAAABSAABAWA
>          AA
>
> AAABCDEAAAAABSAABAWA
>           AA
>
> AAABCDEAAAAABSAABAWA
>               AA
> 
> 7
> 
> 
> 
> > 
> > Many thanks in advance,
> > Chris




More information about the Python-list mailing list