Permutation is an arrangement of objects in a specific order. Order of arrangement of object is very important. The number of permutations on a set of n elements is given by n!. For example, there are 2! = 2*1 = 2 permutations of {1, 2}, namely {1, 2} and {2, 1}, and 3! = 3*2*1 = 6 permutations of {1, 2, 3}, namely {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2} and {3, 2, 1}.
Method 1 (Backtracking)
We can use the backtracking based recursive solution discussed here.
Method 2
The idea is to one by one extract all elements, place them at first position and recur for remaining list.
Python3
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
data = list ( '123' )
for p in permutation(data):
print (p)
|
Output:
['1', '2', '3']
['1', '3', '2']
['2', '1', '3']
['2', '3', '1']
['3', '1', '2']
['3', '2', '1']
Method 3 (Direct Function)
We can do it by simply using the built-in permutation function in itertools library. It is the shortest technique to find the permutation.
Python3
from itertools import permutations
l = list (permutations( range ( 1 , 4 )))
print (l)
|
Output:
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
21 Jan, 2022
Like Article
Save Article