All Permutations of a String in Python (Recursive)

permutation, python, recursion

Solution

The result of permutations will be a collection, let's say a list. It will make your code cleaner if you think this way and if required you can join the results into a single string. A simple example will be

def perms(s):        
    if(len(s)==1): return [s]
    result=[]
    for i,v in enumerate(s):
        result += [v+p for p in perms(s[:i]+s[i+1:])]
    return result


perms('abc')

['abc', 'acb', 'bac', 'bca', 'cab', 'cba']


print('\n'.join(perms('abc')))

abc
acb
bac
bca
cab
cba

Problem

I need a kick in the head on this one. I have the following recursive function defined: ``` def perms(s): if(len(s)==1): return s res = '' for x in xrange(len(s)): res += s[x] + perms(s[0:x] + s[x+1:len(s)]) return res + '\n' ``` perms("abc") currently returns: ``` abccb bacca cabba ``` The desired result is ``` abc acd bac bca cab cba ``` Where am I going wrong here? How can I think about this differently to come up with the solution? Note: I am aware of the itertools function. I am trying to understand how to implement permutations recursively for my own learning. That is why I would prefer someone to point out what is wrong with my code, and how to think differently to solve it. Thanks!

Original source