Imagine that we have a string like: "good university student". We need to make all combinations of words in these string. We also need to add some separator characters in these combinations. For clarification please look at the example bellow:
String: "good university student"
Separators = ["-","+"]
Expected results:
student
university
good
good-university-student
good-university
good-student
university-student
good+university+student
good+university
good+student
university+student
I have tried the following code but the result is not what I’m expecting and I did not get all combinations.
def create_name_combos(mystring):
words = mystring.split()
combos = []
for i in range(len(words) - 1):
for separator in ["-", "+", "&"]:
current_combo = separator.join(words[:i+1] + [separator + words[i+1]])
combos.append(current_combo)
return combos
What would be the best solution to get all of possible combinations?
>Solution :
You can use permutations and combinations from itertools:
import re
from itertools import permutations, chain, combinations
def create_name_combos(mystring):
def gen(arr, separators):
res = set()
for s in arr:
for sep in separators:
x = re.sub(r' ', sep, s)
res.add(x)
return res
def get_subsets(words):
return chain.from_iterable(combinations(words, r) for r in range(1, len(words) + 1))
words = mystring.split()
combos = set()
for subset in get_subsets(words):
for perm in permutations(subset):
combos.add(' '.join(perm))
return sorted(gen(sorted(combos), "-+"))
print(create_name_combos('good university student'))
Prints
[‘good’, ‘good+student’, ‘good+student+university’, ‘good+university’,
‘good+university+student’, ‘good-student’, ‘good-student-university’,
‘good-university’, ‘good-university-student’, ‘student’,
‘student+good’, ‘student+good+university’, ‘student+university’,
‘student+university+good’, ‘student-good’, ‘student-good-university’,
‘student-university’, ‘student-university-good’, ‘university’,
‘university+good’, ‘university+good+student’, ‘university+student’,
‘university+student+good’, ‘university-good’,
‘university-good-student’, ‘university-student’,
‘university-student-good’]