How to find and group similar permutations of 4 digits
<p>I am not good at these, but please bear with me. I have a set of numbers from my database / list, all are 4 digit numbers with the numbers between and include 0000 through 9999.</p>

<p>Say the list is:</p>

<pre><code>[1234, 4354, 6554, 2134, 3214, 5456, 9911, 1199]
</code></pre>

<p>Basically, I want to group them in such a way</p>

<pre><code>1234, 2134, 3214 is group A
6554, 5456 is group B
9911, 1199 is group C
4354 is group D
</code></pre>

<p>where the list items in each group all contain the same numbers - i.e, Group A are all made up of the numbers 1, 2, 3, and 4. Then I will find the len(group A), len(group B), len(group C), len(group D)...
and then sort them in decreasing manner.</p>

<p>How to do it?
And if list is huge, is the method still works ok?</p>

<p>Here's a (tested in Python 2.7.10) solution:</p>

<pre><code>def index(number):
    digits = list(str(number))
    return ''.join(sorted(digits))

groups = {}
numbers = [1234, 4354, 6554, 2134, 3214, 5456, 9911, 1199]

for number in numbers:
    key = index(number)

    if key not in groups:
        groups[key] = []

    groups[key].append(number)

print groups.values() # [[1234, 2134, 3214], [4354], [6554, 5456], [9911, 1199]]
</code></pre>

<p>The key to this solution is to take the digits of each number and sort them, then use that result as the dictionary key. <code>index()</code> is just a succinct way of generating the digit-ordered form of each number.</p>

python permutation