Reputation: 133
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
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
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