So I'm trying to create a program to find all the permutations of every number within 1 to n
So for instance if n = 5, so basically we must find the permutations for [1, 2, 3, 4, 5] and for instance if n = 3, we must find the permutations for [1, 2, 3]. The output must be returned as a tuple.
So now I have this code that returns the permutations if the input is a list only and it works.. but how can I modify it to return all permutations when n: int
is the input...
def permutation(lst):
if len(lst) == 0:
return []
if len(lst) == 1:
return [lst]
l = []
for i in range(len(lst)):
m = lst[i]
remLst = lst[:i] lst[i 1:]
for p in permutation(remLst):
l.append([m] p)
return l
What changes should I make for my code to work?
CodePudding user response:
You can use the range
built-in function:
def permutation(lst):
if isinstance(lst, int):
lst = list(range(1, lst 1))
if len(lst) == 0:
return []
if len(lst) == 1:
return [lst]
l = []
for i in range(len(lst)):
m = lst[i]
remLst = lst[:i] lst[i 1:]
for p in permutation(remLst):
l.append(tuple([m] list(p)))
return tuple(l)
Now both integer and list arguments should work:
print(permutation(3))
or
print(permutation([1, 3, 5]))