Home > Net >  How to get pairwise combinations of words?
How to get pairwise combinations of words?

Time:11-29

Given a string I want pair wise combinations of the words present in the string with blank spaces. For instance for the following string:

string = "This is cat"

I want the following output:

str1 = "This is cat"
str2 = "Thisis cat"
str3 = "This iscat"
str4 = "Thisiscat"

I tried something with itertools. Basically getting all pairwise combinations of True and False:

permutations = list(itertools.product([False, True], repeat=2)

and add the blank spaces based on True.

This is what I'm trying:

 
args = string.split()
permutations = list(itertools.product([False, True], repeat=len(args)-1))

strings = []
for i in range(len(args)-1):
    string = ""
    for permutation in permutations:
            if permutation[i] is True:
                string = string   " "   args[i]
            
            if permutation[i] is False:
                string = string   args[i]
    strings.append(string)

CodePudding user response:

i like the idea using combinations of True and False, and it actualy works (if we may use '_' as a replacement):

from itertools import product

string = "This is a cat"
strings = []

permutations = list(product([False, True], repeat=string.count(' ')))
for permutation in permutations:
    s = string
    for p in permutation:
        s = s.replace(' ','' if p else '_',1)
    strings.append(s.replace('_',' ')) 

>>> strings
'''
['This is a cat',
 'This is acat',
 'This isa cat',
 'This isacat',
 'Thisis a cat',
 'Thisis acat',
 'Thisisa cat',
 'Thisisacat']
  • Related