I tried to make python str generator with condition, but it is not easy to me.
condition is simple.
so i tried below code
for i in combinations_with_replacement('ABC', 7):
for j in permutation(i+("A","B","C","A","B","C","A","B","C","A","B","C",), 19):
test j
I think this code covers all combinations but it contains duplicants.
how can I make it better?
To implement the rule that "each letters must be used at least 4 times" you can create a base pool of 12 characters with 'ABC'
repeated 4 times, and that leaves 19 - 3 x 4 = 7 characters that need to be filled in with any of the letters in 'ABC'
, which can be done with itertools.combinations_with_replacement
. Chain the base pool of 12 characters and the additional pool of 7 characters together to generate distinct permutations with more_itertools.distinct_permutations
:
from itertools import chain, combinations_with_replacement
from more_itertools import distinct_permutations
def string_generator(letters='ABC', min_count=4, length=19):
base = letters * min_count
for extra in combinations_with_replacement(letters, length - len(base)):
yield from map(''.join, distinct_permutations(chain(base, extra)))