Reputation: 1778
Given a String is there any short way in Python 3 to find the different combinations of the space seperated words in that string ?
For eg:
If the input string is 'Peaches Apples Bananas', I want output as:
'Peaches Apples Bananas'
'Peaches Bananas Apples'
'Apples Bananas Peaches'
'Apples Peaches Bananas'
'Bananas Peaches Apples'
'Bananas Apples Peaches'
Upvotes: 0
Views: 211
Reputation: 20689
I think you are looking for itertools.permutations
:
import itertools
for perm in itertools.permutations('Peaches Apples Bananas'.split(' ')):
print(' '.join(perm))
Upvotes: 1
Reputation: 1292
import itertools
string = 'Peaches Apples Bananas'
word_list = string.split(' ')
output = [' '.join(permutation) for permutation in itertools.permutations(word_list)]
Upvotes: 1