使用条件制作高效的Python生成器

问题描述 投票:0回答:1

我尝试制作带有条件的python str生成器,但这对我来说并不容易。

条件简单。

  1. 我有 3 个字母,“A”、“B”和“C”
  2. 每个字母必须至少使用4次。
  3. 总句子长度为19。
  4. 我需要测试所有组合。

所以我尝试了下面的代码

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

我认为这段代码涵盖了所有组合,但它包含重复项。

我怎样才能让它变得更好?

python generator
1个回答
0
投票

要实现“每个字母必须至少使用 4 次”的规则,您可以创建一个 12 个字符的基本池,其中

'ABC'
重复 4 次,这样就剩下 19 - 3 x 4 = 7 个字符需要填充与
'ABC'
中的任何字母一起使用,可以使用
itertools.combinations_with_replacement
来完成。将 12 个字符的基本池和 7 个字符的附加池链接在一起,以使用
itertools.permutations
:

生成它们的所有排列
from itertools import permutations, combinations_with_replacement, chain

def string_generator(letters='ABC', min_count=4, length=19):
    for c in combinations_with_replacement(letters, length - len(letters) * min_count):
        for s in map(''.join, permutations(chain(letters * min_count, c))):
            yield s

演示:在线试用!

© www.soinside.com 2019 - 2024. All rights reserved.