Jay Taylor's notes
back to listing indexAll Permutations of a String in Python (Recursive)
[web search]We started with Q&A. Technical documentation is next, and we need your help.
Whether you're a beginner or an experienced developer, you can contribute.
I need a kick in the head on this one. I have the following recursive function defined:
perms("abc") currently returns:
The desired result is
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
By the way, the
|
|||||||||||||||||||||||||||||||||
|
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
|
|||||||
|
I think you can use this logic: helper function
|
||||
Not sure about efficiency but this should work too.
|
||||
This kind of thing is a nice place for generators (https://docs.python.org/3.3/tutorial/classes.html#generators), and 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.
|
|||||||||||||||
|
Your Answer
asked |
2 years ago |
viewed |
8439 times |
active |
Get the weekly newsletter! In it, you'll get:
- The week's top questions and answers
- Important community announcements
- Questions that need answers
see an example newsletter
Related
Technology | Life / Arts | Culture / Recreation | Science | Other | ||
---|---|---|---|---|---|---|