Reputation: 71
i want all combinations words of character using terms. Example :
word = 'aan'
result = ['ana', 'naa', 'aan']
terms :
number of character 'a' -> 2
number of character 'n' -> 1
Upvotes: 0
Views: 45
Reputation: 71451
You can use recursion with a generator:
from collections import Counter
def combo(d, c = []):
if len(c) == len(d):
yield ''.join(c)
else:
_c1, _c2 = Counter(d), Counter(c)
for i in d:
if _c2.get(i, 0) < _c1[i]:
yield from combo(d, c+[i])
word = 'aan'
print(list(set(combo(word))))
Output:
['aan', 'naa', 'ana']
word = 'ain'
print(list(set(combo(word))))
Output:
['ina', 'nia', 'nai', 'ani', 'ian', 'ain']
Upvotes: 0
Reputation: 59
I tried a one liner solution, and give the result in a list
You can use permutation tools from itertools package to get all of the permutations (not combinations) solutions
from itertools import permutations
word = 'aan'
list(set([ ''.join(list(i)) for i in permutations(word,len(word))]))
Upvotes: 1
Reputation: 318
If I really understand what you want, I would do it like that:
from itertools import permutations
result = set()
for combination in permutations("aan"):
result.add(combination)
Upvotes: 0