473,657 Members | 2,626 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Counting all permutations of a substring

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(targets tr) 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.

Many thanks in advance,
Chris

Apr 5 '06 #1
7 4181

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(targets tr) 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:
print a
print ' '*i+b
print
matches += 1
return matches
ss('AAABCDEAAAA ABSAABAWA','AA' )

AAABCDEAAAAABSA ABAWA
AA

AAABCDEAAAAABSA ABAWA
AA

AAABCDEAAAAABSA ABAWA
AA

AAABCDEAAAAABSA ABAWA
AA

AAABCDEAAAAABSA ABAWA
AA

AAABCDEAAAAABSA ABAWA
AA

AAABCDEAAAAABSA ABAWA
AA

7

Many thanks in advance,
Chris


Apr 5 '06 #2

me********@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(targets tr) 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('AAABCDEAAAA ABSAABAWA','AA' )

AAABCDEAAAAABSA ABAWA
AA

AAABCDEAAAAABSA ABAWA
AA

AAABCDEAAAAABSA ABAWA
AA

AAABCDEAAAAABSA ABAWA
AA

AAABCDEAAAAABSA ABAWA
AA

AAABCDEAAAAABSA ABAWA
AA

AAABCDEAAAAABSA ABAWA
AA

7

Many thanks in advance,
Chris


Apr 5 '06 #3

On Apr 5, 2006, at 5:07 PM, 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(targets tr) 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.

I don't think you're describing a permutation. A permutation of a
string 'ABC' would be 'CBA', or 'BCA'.

You're describing something like the number of proper substrings of a
given value, and the easiest way to do that is to just check to see if
the probestring starts a string at the current index of the string...

def count_proper_su bstrings_equal_ to(target, probe):
i = 0
count = 0
while i < len(target):
if target[i:].startswith(pro be):
count = count + 1
i = i + 1
return i

And of course there's a more 'pythonic' way to do it, but this would
be a generalized algorithm suitable for most languages.

---
Andrew Gwozdziewycz
ap****@gmail.co m
http://ihadagreatview.org
http://and.rovir.us
Apr 5 '06 #4
[counting all (possibly overlapping) occurences of a substring in a string]

def count_subs(s,su bs,pos=0) :
pos = 1+s.find(subs,p os)
return pos and 1+count_subs(s, subs,pos)

or equivalently

def count_subs(s,su bs)
pos,cnt = 0,0
while True :
pos = 1+s.find(subs,p os)
if not pos :
return cnt
cnt += 1

or even (using the helper functions of my last post in the "small
challenge" thread)

def count_subs(s,su bs) :
cnt = 0
for pos1 in echoback(1+s.fi nd(subs,pos) for pos in itially(0)) :
if not pos1 :
return cnt
cnt += 1
(I've minimally tested only the first version)
Apr 6 '06 #5
Great suggestions, guys! Thanks so much!

And yes, I stand corrected. A better suited subject title would have
been "Counting all overlapping substrings".

Thanks again,
Chris

Apr 6 '06 #6
I wrote:
[counting all (possibly overlapping) occurences of a substring in a string]

def count_subs(s,su bs,pos=0) :
pos = 1+s.find(subs,p os)
return pos and 1+count_subs(s, subs,pos) .


now to push lisp-style to the extreme, a recursive one-liner solution
with presumably better stack behavior (assuming proper tail-recursion
elimination, which I doubt is the case in Python).

Python 2.5a1 (r25a1:43589, Apr 5 2006, 10:36:43) [MSC v.1310 32 bit
(Intel)] on win32
....
cnt_ss = lambda s,ss,p=-1,n=-1 : n if n>p else cnt_ss(s,ss,s.f ind(ss,p+1),n+1 )
cnt_ss("AABBAAA BABAAA","AA") 5 cnt_ss("foolish ","bar") 0 cnt_ss("banana split","ana")

2

note though that the first solution beats this one on token count: 37 vs 42
Apr 6 '06 #7
Azolex wrote:
Python 2.5a1 (r25a1:43589, Apr 5 2006, 10:36:43) [MSC v.1310 32 bit
(Intel)] on win32
...
cnt_ss = lambda s,ss,p=-1,n=-1 : n if n>p else cnt_ss(s,ss,s.f ind(ss,p+1),n+1 )


<sarcastic-mode>
Ah, the pleasure of having a ternary operator in the language!
</sarcastic-mode>

Michele Simionato

Apr 6 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
6723
by: cassandra.flowers | last post by:
Hi, I have another string handling question for the group, since you have all been so helpful in the past. Thank you. Basically, I want to do something really simple: Search a main string for a substring, then count how many times the
10
5663
by: Steve Goldman | last post by:
Hi, I am trying to come up with a way to develop all n-length permutations of a given list of values. The short function below seems to work, but I can't help thinking there's a better way. Not being a computer scientist, I find recursive functions to be frightening and unnatural. I'd appreciate if anyone can tell me the pythonic idiom to accomplish this. Thanks for your help,
8
2155
by: RickMuller | last post by:
I have to sort a list, but in addition to the sorting, I need to compute a phase factor that is +1 if there is an even number of interchanges in the sort, and -1 if there is an odd number of interchanges. I could write a bubble sort, count the number of interchanges, and compute the factor, but I have a feeling that there some decorate-sort-undecorate solution buried in this problem somewhere. However, I can't see it. Can anyone else...
4
6566
by: Victor Engmark | last post by:
When looking for a method to fetch unique elements and counting the number of occurences of each of them, I found quite a lot of gross examples of complex XSL. But after realizing the subtle difference between "." and "current()", I found a neat way of doing the same without keys or generate-id(): <xsl:template match="/"> <!-- Selects all "new" elements --> <xsl:for-each select="//Name"> <!-- Display the element -->
20
2283
by: John Trunek | last post by:
I have a set of X items, but want permutations of length Y (X > Y). I am aware of the permutation functions in <algorithm>, but I don't believe this will do what I want. Is there a way, either through the STL or some other library to do this, or do I need to write my own code?
3
2420
by: sparks | last post by:
Besides doing a loop is there a command that will give the number of occurreneces of a chr in a string? The only way I can think of is to do a while loop and count variable. thanks for info Jerry
5
2842
by: Anders K. Jacobsen [DK] | last post by:
Hi We have a rather large asp.net project with serveral utility projects (written in C#). Is there at tool out there which can give an estimate of the total amount of code lines all projects results in? thanks in regads Anders
0
1363
by: jmbn2k | last post by:
HI Can anyone get me the code for counting and listing all permutaions of aphabets which would be displayed if any 3 buttons of our cell phone is pressed..................thanx
82
3649
by: Bill Cunningham | last post by:
I don't know if I'll need pointers for this or not. I wants numbers 10^16. Like a credit card 16 digits of possible 10 numbers, so I guess that would be 10^16. So I have int num ; These are of course declared and not initialized. Now I want to initialize them all with '\0'. That I'm guessing would involve while ( --). Or maybe for. Would pointers be involved in this? With this excercise I would learn working with multi-dimensional
0
8385
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8303
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8821
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8502
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8602
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1941
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1601
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.