'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?



Solution 1:[1]

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']

Solution 2:[2]

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.

Solution 3:[3]

After applying the StringToWordVector, ensure that you select the correct attribute (class in your case) on the Classify tab. By default, the Explorer selects the last one. However, the StringToWordVector filter moves any class attribute to the start and therefore a word attribute, which is most likely numeric, will be selected automatically as the class.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Soroosh Noorzad
Solution 2 Akintoye Arogunmati
Solution 3 fracpete