Memory error python computing permutations of list
<p>I want to compute all possible ways of constructing a binary list of length n with the following line</p>

<pre><code>combinations = map(list, itertools.product([0, 1], repeat=n))
</code></pre>

<p>This works fine with low n's but I want to compute this for big n's (i.e. values between 25-35). Is there a better and more efficient way of producing this list? </p>

<p>Your are trying to find all the combinations of 0 and 1 for n term. Total number of such combination will be <code>2**n</code>. For <code>n=30</code>, total such combinations are <code>1073741824</code>. Huge isn't? </p>

<p>In order to get rid of the memory error, you should be using <a href="https://wiki.python.org/moin/Generators" rel="nofollow">generator</a>  which <code>yield</code> the combinations dynamically instead of storing these as list. Also, since it is the combination of just 0s and 1s. Why not print binary numbers from <code>0</code> to <code>'1'*n</code>?</p>

<p>Below is the iterator to achieve this as:</p>

<pre><code>def binary_combinations(num):
    my_binary_string = '1'*num
    my_int_num = int(my_binary_string, 2)
    format_string = '{'+':0{}b'.format(num)+'}'
    for i in xrange(my_int_num):
        yield format_string.format(i)
    else:
        raise StopIteration('End of Memory Issue!')
</code></pre>

<p>In order to execute this, do:</p>

<pre><code>&gt;&gt;&gt; for i in binary_combinations(3):
...     print i
...
000
001
010
011
100
101
110
</code></pre>

<p>Here <code>n = 3</code>. Now you may use it with n = 30, 40, .. OR whatever you want ;)</p>

python python-2.7 permutation combinatorics