Im having trouble trying to make a permutation code with recursion. This is suppose to return a list back to the use with all the posible position for each letter. so for the word cat
it is suppose to return ['cat','act',atc,'cta','tca','tac']
. so far i have this
def permutations(s):
lst=[]
if len(s) == 1 or len(s) == 0 :
# Return a list containing the string, not the string
return [s]
# Call permutations to get the permutations that don't include the
# first character of s
plst = permutations(s[1:])
print(plst)
for item in plst:
print (item)
plst= permutations(s[1+1:])
# Now move through each possible position of the first character
# and create a new string that puts that character into the strings
# in plst
for i in range(len(s)):
pass
# Create a new string out of item
# and put it into lst
# Modify
for item in lst:
print(index)
There are steps there but im not sure how to use them
This is the easiest solution I came up with.
You can test it with:
You want to do recursion, so you first have to find out how the recursion would work. In this case it is the following:
And as a final condition:
So the recursion splits up the list in sublists with one element extracted each time. Then this element is added to the front of each of the permutations of the sublist.
So in pseudo-code:
Does this help?
When you're lost in recursive function, you should draw the call tree. The following version (inspired @Ben answer) keep the input order (if the input is in lexicographic order, the list of permutations will be,
'012' -> ['012', '021', '102', '120', '201', '210']
.The following version works for strings and lists, notice the reconstruction step is not the same:
As an exercice, you should draw call tree of the these functions, do you notice something ?
I know this is a me too, but I think this one might be easier for some folks to understand....
def permute(s):
Recursively, think about the base case and build from that intuition.
1) What happens when there's only one character 'c'? There's only one permutation of that element, and so we return a list containing only that element.
2) How can we generate the next permutation given the last one? Adding an additional letter 'a' at all possible positions in the previous permutation 'c' gives us 'ca', 'ac'.
3) We can continue building larger and larger permutations by adding an additional character at all possible positions in each earlier permutation.
The following code returns a list of one character if the string has one character or less. Otherwise, for all permutations not including the last character in the string s[-1], we generate a new string for each position where we could include that character and append the new string to our current list of permutations.
You can call it by