Permutations of 2 characters in Python into fixed length string with equal numbers of each character
<p>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.</p>

<p><a href="http://stackoverflow.com/questions/36517439/permutation-of-x-length-of-2-characters">Permutation of x length of 2 characters</a></p>

<p><a href="http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python">How to generate all permutations of a list in Python</a></p>

<p>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. Additionally - I need each character to be represented 20 times in the string. So all resulting strings each have 20 'A's and 20 'B's.</p>

<p>Like this:</p>

<pre><code>'AAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBB'
'AAAAAAAAAAAAAAAAAAABABBBBBBBBBBBBBBBBBBB'
'AAAAAAAAAAAAAAAAAABAABBBBBBBBBBBBBBBBBBB'
</code></pre>

<p>etc...</p>

<p>All I really need is the count of unique combinations that follow these rules. </p>

<pre><code>y=['A','A','A','A','B','B','B','B']
comb = set(itertools.permutations(y))
print("Combinations Found: {:,}".format(len(comb)))
</code></pre>

<p>This works, but it doesn't scale well to an input string of 20 'A's and 20 'B's. The above code takes 90 seconds to execute. Even just scaling up to 10 'A's and 10 'B's ran for 20 minutes before I killed it.</p>

<p>Is there more efficient way to approach this given the parameters I've described?</p>

<p>If all you need is the count, this can be generalized to <a href="https://en.wikipedia.org/wiki/Binomial_coefficient" rel="nofollow"><code>n</code> choose <code>k</code></a>.  Your total size is <code>n</code> and the number of elements of <code>"A"</code> is <code>k</code>.  So, your answer would be:</p>

<p>(n choose k) = (40 choose 20) = <a href="http://www.wolframalpha.com/input/?i=40+choose+20" rel="nofollow">137846528820</a></p>

python string algorithm permutation