[英]Permutations of 2 characters in Python into fixed length string with equal numbers of each character
I've looked through the 2 questions below, which seem closest to what I am asking, but don't get me to the answer to my question. 我已经仔细阅读了以下两个问题,这些问题似乎与我要问的问题最接近,但是却无法帮助我找到问题的答案。
Permutation of x length of 2 characters x长度为2个字符的排列
How to generate all permutations of a list in Python 如何在Python中生成列表的所有排列
I am trying to find a way to take 2 characters, say 'A' and 'B', and find all unique permutations of those characters into a 40 character string. 我试图找到一种方法来接受两个字符,例如“ A”和“ B”,并找到这些字符的所有唯一排列成40个字符串。 Additionally - I need each character to be represented 20 times in the string.
另外-我需要每个字符在字符串中表示20次。 So all resulting strings each have 20 'A's and 20 'B's.
因此,所有生成的字符串每个都有20个“ A”和20个“ B”。
Like this: 像这样:
'AAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBB'
'AAAAAAAAAAAAAAAAAAABABBBBBBBBBBBBBBBBBBB'
'AAAAAAAAAAAAAAAAAABAABBBBBBBBBBBBBBBBBBB'
etc... 等等...
All I really need is the count of unique combinations that follow these rules. 我真正需要的是遵循这些规则的独特组合的数量。
y=['A','A','A','A','B','B','B','B']
comb = set(itertools.permutations(y))
print("Combinations Found: {:,}".format(len(comb)))
This works, but it doesn't scale well to an input string of 20 'A's and 20 'B's. 这可以工作,但不能很好地缩放到20'A和20'B的输入字符串。 The above code takes 90 seconds to execute.
上面的代码执行需要90秒。 Even just scaling up to 10 'A's and 10 'B's ran for 20 minutes before I killed it.
在我杀死它之前,甚至只是扩大到10'A和10'B都跑了20分钟。
Is there more efficient way to approach this given the parameters I've described? 给定我描述的参数,是否有更有效的方法来解决此问题?
If all you need is the count, this can be generalized to n
choose k
. 如果您只需要计数,则可以将其推广为
n
选择k
。 Your total size is n
and the number of elements of "A"
is k
. 您的总大小为
n
,而"A"
的元素数为k
。 So, your answer would be: 因此,您的答案将是:
(n choose k) = (40 choose 20) = 137846528820 (n选择k)=(40选择20)= 137846528820
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.