简体   繁体   中英

How can I count the number of ways to divide a string into N parts of any size?

I'm trying to count the number of ways you can divide a given string into three parts in Python.

Example: "bbbbb" can be divided into three parts 6 ways:

  1. b|b|bbb
  2. b|bb|bb
  3. b|bbb|b
  4. bb|b|bb
  5. bb|bb|b
  6. bbb|b|b

My first line of thinking was N choose K , where N = the string's length and K = the number of ways to split (3), but that only works for 3 and 4.

My next idea was to iterate through the string and count the number of spots the first third could be segmented and the number of spots the second third could be segmented, then multiply the two counts, but I'm having trouble implementing that, and I'm not even too sure if it'd work.

How can I count the ways to split a string into N parts?

Think of it in terms of the places of the splits as the elements you're choosing:

b ^ b ^ b ^ ... ^ b

^ is where you can split, and there are N - 1 places where you can split ( N is the length of the string), and, if you want to split the string into M parts, you need to choose M - 1 split places, so it's N - 1 choose M - 1 .

For you example, N = 5 , M = 3 . (N - 1 choose M - 1) = (4 choose 2) = 6 .

An implementation:

import scipy.special

s = 'bbbbb'
n = len(s)
m = 3
res = scipy.special.comb(n - 1, m - 1, exact=True)

print(res)

Output:

6

I came up with a solution to find the number of ways to split a string in python and I think it is quite easier to understand and has a better time complexity

def slitStr(s):
  i = 1
  j= 2
  count = 0
  while i <= len(s)-2: 
    # a, b, c are the split strings
    a = s[:i]
    b = s[i:j]
    c = s[j:]
    #increase j till it gets to the end of the list 
    #each time j gets to the end of the list increment i
    #set j to i + 1
    if j<len(s):
        j+= 1
        if j==len(s):
            i += 1
            j = i+1
    # you can increment count after each iteration
    count += 1

You can customize the solution to fit your need. I hope this helps.

Hope this helps you too:

string = "ABCDE"
div = "|"
out = []
for i in range(len(string)):
    temp1 = ''
    if 1 < i < len(string):
        temp1 += string[0:i-1] + div
        for j in range(len(string) + 1):
            temp2 = ""
            if j > i:
                temp2 += string[i-1:j-1] + div + string[j-1:]
                out.append(temp1 + temp2)
print(out)

Result:

['A|B|CDE', 'A|BC|DE', 'A|BCD|E', 'AB|C|DE', 'AB|CD|E', 'ABC|D|E']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM