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!
There you go (recursive permutation):
In order to get a list of all permutation strings, simply call the function above with your input string. For example,
In order to get a single string of all permutation strings separated by new-line characters, simply call
'\n'.join
with the output of that function. For example,By the way, the
print
results for the two options above are identical.This kind of thing is a nice place for generators (https://docs.python.org/3.3/tutorial/classes.html#generators), and
yield
.Try something like this (not tested):
This is the classic permutation algorithm: you keep the first character and prepend it to all permutations of the remaining characters. This particular function is a python generator: that means it can keep running while yielding its results one-by-one. In this case, it makes it easier to concentrate on the algorithm without worrying about the details of how to get the data back to the caller.
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
Not sure about efficiency but this should work too.
Here is the code: