Python Permutation taken at a time
Question: I wrote nested loops to give me all posible permutations of all letter of
alphabet taken 4 letters at a time.

    
    
    def permutation():
    
        import string
        alphabet = string.ascii_lowercase
    
        perm = []
    
        for item1 in alphabet:
            for item2 in alphabet:
                for item3 in alphabet:
                    for item4 in alphabet:
                        perm += [item1 + item2 + item3 + item4]
    
        return perm
    

So, when I do

    
    
    permutation() 
    

I get

    
    
    ['aaaa',
    'aaab',
    'aaac',
    'aaad',
    'aaae',
     ...
    'zzzz']
    

Although this solves my particular problem (4 digit permutation), it's not an
neat solution. Furthermore, if I'd like to make a n digit permutation (say, 10
digits), the nested loops would be a mess.

So, I was thinking I you can tell me how to implement this nested loops as
some kind of function, using recursion or something of the sort.

By the way, I know that in this particular problem (4 digit permutation), I
could use python libraries:

    
    
    def permutation():
    
        from itertools import product
        import string
        alphabet = string.ascii_lowercase
    
        perm = [ ''.join(p) for p in list(product(list(alphabet),repeat = 4)) ]
    
        return perm
    

and this is what I would use in real life, but here I'm trying to figure out
the algorithm of the permutation of letters of alphabet taken n letters at a
time.


Answer: First, break this down into the two basic points of recursion: degenerate step
(final condition) and recursion step. Here, our final condition is to return
the alphabet when we want strings of length 1.

For longer strings (length n), prepend each letter of the alphabet to all
permutations of length n-1.

    
    
    import string
    alphabet = string.ascii_lowercase
    
    def permutation(n):
        return [c for c in alphabet] if n == 1 \
            else [c + n_perm for c in alphabet for n_perm in permutation(n-1)]
    
    print permutation(1)
    print permutation(2)
    

