我正在尝试生成类似于“0000011111”或“000 11 2222 333”这样的字符串的所有可能排列。我尝试使用itertools中的permutations对“0000011111”进行操作,如下所示:
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))
但是当排列只有10个C5 = 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 the next 0 over one "0010 0111" -> "0010 1011"
...
Until you get to "1111 0000".
Then for each of the strings generated, repeat the process with 2's.
222 xxxx xxxx -> 22x 2xxx xxxx -> 22x x2xx xxx...
我是不是最好只做set(perms)来去除重复项?(我需要排列由3-5个字符组成的20个字符列表,其中itertools permutations会给我10e18个字符串)
我已经业余编程三年了,但只知道与一个学期的编程课程相当的知识。