n0rd
n0rd

Reputation: 133

Add words together to form all possible combinations

So I have recently picked up python and I am trying to get all the different combinations of multiple words. I have been looking at itertools, but have failed to achieve my desired result. It is easier explained with a practical example. This is what I am trying to accomplish:

somestring = "cat, cake, apples"
result = itertools magik
print result

>>> catcake, catapples, cakecat, cakeapples, applescat, applescake

So far this is the closest I have gotten to achieving this, but it does not return every iteration possible:

from itertools import combinations
print ["".join(a) for a in combinations(["cat", "cake", "apples"], 2)]

>>> ['catcake', 'catapples', 'cakeapples']

Any help would be much appreciated.

Upvotes: 0

Views: 101

Answers (2)

MSeifert
MSeifert

Reputation: 152725

You are actually looking for permutations not combinations:

>>> print(["".join(a) for a in permutations(["cat", "cake", "apples"], 2)])
['catcake', 'catapples', 'cakecat', 'cakeapples', 'applescat', 'applescake']

Upvotes: 1

Rafael Aguilar
Rafael Aguilar

Reputation: 3279

This should work

from itertools import permutations
print ["".join(a) for a in permutations(["cat", "cake", "apples"], 2)]
#['catcake', 'catapples', 'cakecat', 'cakeapples', 'applescat', 'applescake']

This happens because in combinations order doesn't matters, in permutations do matter, e.g.:

'(cat,cake)' == '(cake, cat)' # Combinations
'(cat,cake)' != '(cake, cat)' # Permutations

Upvotes: 1

Related Questions