Search code examples
pythongenerator

make efficient python generator with condition


I tried to make python str generator with condition, but it is not easy to me.

condition is simple.

  1. I have 3 letters, "A", "B", and "C"
  2. each letters must be used at least 4 times.
  3. total sentence length is 19.
  4. I need to test all combinations.

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?


Solution

  • 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)))
    

    Demo: https://replit.com/@blhsing1/SandyNimblePatches