Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a lazy one-liner, also using itertools:</p> <pre><code>from itertools import compress, product def combinations(items): return ( set(compress(items,mask)) for mask in product(*[[0,1]]*len(items)) ) # alternative: ...in product([0,1], repeat=len(items)) ) </code></pre> <p>Main idea behind this answer: there are 2^N combinations -- same as the number of binary strings of length N. For each binary string, you pick all elements corresponding to a "1".</p> <pre><code>items=abc * mask=### | V 000 -&gt; 001 -&gt; c 010 -&gt; b 011 -&gt; bc 100 -&gt; a 101 -&gt; a c 110 -&gt; ab 111 -&gt; abc </code></pre> <p>Things to consider:</p> <ul> <li>This requires that you can call <code>len(...)</code> on <code>items</code> (workaround: if <code>items</code> is something like an iterable like a generator, turn it into a list first with <code>items=list(_itemsArg)</code>)</li> <li>This requires that the order of iteration on <code>items</code> is not random (workaround: don't be insane)</li> <li>This requires that the items are unique, or else <code>{2,2,1}</code> and <code>{2,1,1}</code> will both collapse to <code>{2,1}</code> (workaround: use <code>collections.Counter</code> as a drop-in replacement for <code>set</code>; it's basically a multiset... though you may need to later use <code>tuple(sorted(Counter(...).elements()))</code> if you need it to be hashable)</li> </ul> <hr> <p><strong>Demo</strong></p> <pre><code>&gt;&gt;&gt; list(combinations(range(4))) [set(), {3}, {2}, {2, 3}, {1}, {1, 3}, {1, 2}, {1, 2, 3}, {0}, {0, 3}, {0, 2}, {0, 2, 3}, {0, 1}, {0, 1, 3}, {0, 1, 2}, {0, 1, 2, 3}] &gt;&gt;&gt; list(combinations('abcd')) [set(), {'d'}, {'c'}, {'c', 'd'}, {'b'}, {'b', 'd'}, {'c', 'b'}, {'c', 'b', 'd'}, {'a'}, {'a', 'd'}, {'a', 'c'}, {'a', 'c', 'd'}, {'a', 'b'}, {'a', 'b', 'd'}, {'a', 'c', 'b'}, {'a', 'c', 'b', 'd'}] </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload