![]() Now len() is 2, hence the else branch of the if is taken. This is trivial, since len(') is 1 then the first branch of the if condition is taken and the return value is itself (this complies with rule 2.1). Now we try to 'mental execute' it in order to shed some light for the absolute beginner. The program is a straightforward (possibly inefficient, see the remarks at the bottom of the page) implementation of the recursive algorithm. def getpermutation (word, base): if len (word) 0: lst.append (base) Add current permutation to end of list. def getpermutationslist (word, base ''): lst Create a list to hold permutations. Trying to Understand the Code by 'Mental Execution' If you want a single function that returns the whole list, with everything enclosed it can be done as follows. ![]() Such code is not mine, it is the original snippet the OP was asking for explanations (as a matter of fact, I am more inclined towards Lua than Python and I had to lookup the enumerate function in Python's documentation in order to fully understand the code). Python has a built-in data type called list. Let's first have a quick look over what is a list and what is permutation in Python. We will use some built-in functions and some custom codes as well. Size of permutation array equals the size of the array. Push number 3 at position 2.Mark position 2 as Taken. Position 0 and 1 ( Taken ), Position 2 ( Available ) Push number 2 at position 1.Mark position 1 as Taken. Also, there's no need to create a new list to hold permutations at each level of the recursion. Position 0 ( Taken ), Position 1 ( Available ) As Unmitigated has pointed out, you need to add a copy of the permuted list. Push number 1 at position 0.Mark position 0 as Taken. Remove the element at position ‘p’ from the Permutation.īelow recursion stack explains how the algorithm works. Generate_Permutation ( Permutation, Array, Positions ) If element at position ‘p’ has been takenĪppend the element at position ‘p’ to the Permutation.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |