Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Starting with Python 2.6</strong> (and if you're on Python 3) you have a <strong>standard-library</strong> tool for this: <a href="https://docs.python.org/2/library/itertools.html#itertools.permutations" rel="noreferrer"><code>itertools.permutations</code></a>.</p> <pre><code>import itertools list(itertools.permutations([1, 2, 3])) </code></pre> <hr> <p>If you're using an <strong>older Python (&lt;2.6)</strong> for some reason or are just curious to know how it works, here's one nice approach, taken from <a href="http://code.activestate.com/recipes/252178/" rel="noreferrer">http://code.activestate.com/recipes/252178/</a>:</p> <pre><code>def all_perms(elements): if len(elements) &lt;=1: yield elements else: for perm in all_perms(elements[1:]): for i in range(len(elements)): # nb elements[0:1] works in both string and list contexts yield perm[:i] + elements[0:1] + perm[i:] </code></pre> <p>A couple of alternative approaches are listed in the documentation of <code>itertools.permutations</code>. Here's one:</p> <pre><code>def permutations(iterable, r=None): # permutations('ABCD', 2) --&gt; AB AC AD BA BC BD CA CB CD DA DB DC # permutations(range(3)) --&gt; 012 021 102 120 201 210 pool = tuple(iterable) n = len(pool) r = n if r is None else r if r &gt; n: return indices = range(n) cycles = range(n, n-r, -1) yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i+1:] + indices[i:i+1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] yield tuple(pool[i] for i in indices[:r]) break else: return </code></pre> <p>And another, based on <code>itertools.product</code>:</p> <pre><code>def permutations(iterable, r=None): pool = tuple(iterable) n = len(pool) r = n if r is None else r for indices in product(range(n), repeat=r): if len(set(indices)) == r: yield tuple(pool[i] for i in indices) </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. 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.
 

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