I think ... - syntaxhttps://blog.kmonsoor.com/2014-01-31T00:00:00+06:00Python - How to Create All Possible Combinations (a.k.a Permutations)2014-01-31T00:00:00+06:002014-01-31T00:00:00+06:00Khaled Monsoortag:blog.kmonsoor.com,2014-01-31:/python-how-to-generate-all-possible-combinations-or-permutations/<p>Let’s say we have a string, or number. And, we want to generate all the combinations of all the characters of the string or the number</p><p>Let’s say the number is 123.</p>
<p>Then the statement:
<div class="highlight"><pre><span></span><code><span class="linenos" data-linenos="1 "></span><span class="p">[</span><span class="nb">int</span><span class="p">(</span><span class="s1">''</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">x</span><span class="p">))</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">permutations</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="mi">123</span><span class="p">)))]</span>
</code></pre></div>
will create a sorted list of all possible numbers using ‘1’,‘2’ and ‘3’.
which is, [123, 132, 213, 231, 312, 321]</p>
<h3 id="what-it-is-doing">What it is doing<a class="headerlink" href="#what-it-is-doing" title="Permanent link">¶</a></h3>
<p>The part, <code>permutations(list(str('123'</code> is creating a <a href="https://en.wikipedia.org/wiki/Permutation">permutated</a> <a href="https://en.wikipedia.org/wiki/Tuple">tuples’</a> list of splitted string ‘123’.
And the <code>int(''.join(x))</code> is converting each tuple to Integer.</p>
<p>However, of course, you need to <code>import permutations from itertools</code>.</p>
<p>so, the generalized version would be:</p>
<div class="highlight"><pre><span></span><code><span class="linenos" data-linenos="1 "></span><span class="kn">from</span> <span class="nn">itertools</span> <span class="kn">import</span> <span class="n">permutations</span>
<span class="linenos" data-linenos="2 "></span><span class="p">[</span><span class="nb">int</span><span class="p">(</span><span class="s1">''</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">x</span><span class="p">))</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">list</span><span class="p">(</span><span class="n">permutations</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">n</span><span class="p">))))]</span>
</code></pre></div>
<p>Python is fun. Isn’t it?</p>