I want to create a recursive algorithm that will generate all permutations
of a specified length of a list of integers with some length n.
Following is my idea:
For every element in the list, I can remove it, then ask my recursive function to return to me all permutations of length k-1, and then to each of those permutations I will add the removed number. Then repeat this process for all numbers in the list.
The base cases are when the list is empty or contains only one element.
In these cases I just return the list. That is, as long as k is less than or equal to the length of the list (ex. if k is 3, but l = [1,2], I can't produce any permutations of length k).
This is what I've written:
def permutations(l, k):
w = len(l)
if (k <= w): # list is bigger than the length each permutations
if (w <= 1):
return list(l)
else:
result = []
for element in l:
listSmaller = l[:element] + l[element+1:]
for perm in permutations(listSmaller, k-1):
result.append([perm] + element)
return result
else: # list is not bigger than the length of the permutations, impossible.
print("k cannot exceed length of list")
I keep getting TypeError: can only concatenate list (not "int") to list
How should I modify this?
itertoolsmodule? docs.python.org/3/library/itertools.htmlpermutationswhich are resulting in the reported error? Thanks!for element in l:, theelementis no more an index starting from 0 but the individual elements of the listl, one at a time. Now while accessing the elements of the listlyou can't use,l[:element]orl[element+1:]. You need an index which you can get using enumerate asfor i, element in enumerate(l):and then you can usel[:i] + l[i+1:]