我正在尝试生成诸如“0000011111”或“000 11 2222 333”之类的字符串的所有可能排列。我尝试在“0000011111”上使用itertools 的排列,如下所示:
from itertools import permutations
basestring = "0"*5 +"1"*5
perms = [''.join(p) for p in permutations(basestring)]
print(len(perms), perms)
print(len(set(perms)), set(perms))
Run Code Online (Sandbox Code Playgroud)
但是当只有 10 个 C 5 = 252个排列时,列表perms有300 万个条目。
是否有我可以使用的内置工具可以更好地处理具有许多重复字符的字符串的排列?
否则这个算法如何生成排列(对于“0000 1111 222”)?
Start with 2 characters "0000 1111"
Move right most 0 over one "0001 0111" and add it to the list
Continue moving it to the end "0001 1011" -> "0001 1101" -> "0001 1110"
Now move …Run Code Online (Sandbox Code Playgroud)