我尝试制作带有条件的python str生成器,但这对我来说并不容易。
条件简单。
所以我尝试了下面的代码
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
我认为这段代码涵盖了所有组合,但它包含重复项。
我怎样才能让它变得更好?
要实现“每个字母必须至少使用 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
演示:在线试用!