Is there a permutation function in python?

Permutations means different orders by which elements can be arranged. The elements might be of a string, or a list, or any other data type. It is the rearrangement of items in different ways. Python has different methods inside a package called itertools, which can help us achieve python permutations. 

For example, if we have three balls – RED BLUE YELLOW 

We can make different arrangements for this ball. 

  • RED BLUE YELLOW  
  • RED YELLOW BLUE 
  • YELLOW RED BLUE 
  • YELLOW BLUE RED 
  • BLUE RED YELLOW 
  • BLUE YELLOW RED  

These all are possible arrangements where the order is essential and there is no repetition, and this is known as permutation. 

  • Syntax of python permutations
    • Parameters- 
  • Example for Simple Python Permutation
  • Using Python Permutations function on a String 
  • Find the order in lexicographical sorted order 
  • Using python permutations function on a list 
  • Python Permutation without built-in function for String
  • Python Permutation without built-in function for Lists
  • Must Read
  • Conclusion

Syntax of python permutations

Python has a package called ‘itertools’ from which we can use the permutations function and apply it on different data types. The number of total permutation possible is equal to the factorial of length [number of elements]. In our case, as we have 3 balls, 3! = 3*2*1 = 6.  

To import permutations[] – from itertools import permutations 

Parameters- 

  1. Iterable – Here, we have to pass the iterable of whose permutations we want. Example of iterables- list, tuple, string, etc.   
  2. Size- In this parameter, we have to specify the number of elements in each permutation.

Example for Simple Python Permutation

from itertools import permutations 
a=permutations [[1,2,3],2] 
for i in a: 
  print[i] 

Output- 
[1, 2] 
[1, 3] 
[2, 1] 
[2, 3] 
[3, 1] 
[3, 2] 

If we do not pass any argument in the second parameter, the default value is set as the length of the iterable. 

For example- 

from itertools import permutations 
a=permutations[[1,2,3]] 
for i in a: 
   print[i] 

Output- 
[1, 2, 3] 
[1, 3, 2] 
[2, 1, 3] 
[2, 3, 1] 
[3, 1, 2] 
[3, 2, 1] 

You must be wondering why we are saving the result in a variable and printing the result using a ‘for’ loop. Let’s see what if we print the variable.  

from itertools import permutations 
a=permutations[[1,2,3]] 
print[a] 

Output- 
  

We are getting this object as an output. So, we have to use a for loop to iterate through this variable and get the result.  

Another way to get the output is making a list and then printing it. 

from itertools import permutations 
print[list[permutations[[1,2,3]]]] 

Output- 
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] 

Using Python Permutations function on a String 

If we want to find different orders in which a string can be arranged, we can use the permutations function. Let us see how- 

string="ASHU" 
a=permutations[string] 
for i in list[a]: 
   # join all the letters of the list to make a string 
   print["".join[i]] 

Output- 
ASHU 
ASUH 
AHSU 
AHUS 
AUSH 
AUHS 
SAHU 
SAUH 
SHAU 
SHUA 
SUAH 
SUHA 
HASU 
HAUS 
HSAU 
HSUA 
HUAS 
HUSA 
UASH 
UAHS 
USAH 
USHA 
UHAS 
UHSA 

If we want to order these elements in the group of two, we can do the following- 

string="ABC" 
a=permutations[string,2] 
for i in list[a]: 
   # join all the letters of the list to make a string 
   print["".join[i]] 

Output- 
AB 
AC 
BA 
BC 
CA 
CB 

You can notice that the total number of results are equal to the factorial of the size we are giving to 2nd parameter. 

Find the order in lexicographical sorted order 

If we want to find all the permutations of a string in a lexicographically sorted order means all the elements are arranged in alphabetical order and if the first element is equal then sorting them based on the next elements and so on. 

from itertools import permutations 
string,n = input[“Enter string and size”].split[] 
print[*[''.join[i] for i in permutations[sorted[string],int[n]]],sep='\n'] 

Output 
Enter the string and size BAC 2 
AB 
AC 
BA 
BC 
CA 
CB 

Using python permutations function on a list 

Now, if we want to find all the possible orders in which a list can be arranged, we can use the similar approach as we did for string. 

a=permutations[[1,2,3,4],2] 
for i in a: 
   print[i] 

Output- 
[1, 2] 
[1, 3] 
[1, 4] 
[2, 1] 
[2, 3] 
[2, 4] 
[3, 1] 
[3, 2] 
[3, 4] 
[4, 1] 
[4, 2] 
[4, 3] 

We can also find the number of ways in which we can reorder the list using a single line of code- 

print[len[list[permutations[[1,2,3,4],4]]]] 

Output- 
24 

Python Permutation without built-in function for String

If we do not want to use the built-in function, we can make some function to achieve this goal. 

answer=[] 
def permutation[string, i, length]:   
   if i == length:   
        answer.append[''.join[string] ]  
   else:   
       for j in range[i, length]:   
           string[i], string[j] = string[j], string[i]   

          #keep increasing i by 1 till it becomes equal to 0 
            permutation[string, i + 1, length]   
           string[i], string[j] = string[j], string[i]   
permutation[list[string], 0, len[string]]  
string="ABC" 
print[str[answer]] 

Output- 
['ABC', 'ACB', 'BAC', 'BCA', 'CBA', 'CAB'] 

Python Permutation without built-in function for Lists

def permutation[list1]:  
   # If the length of list=0 no permuataions possible 
   if len[list1] == 0:  
       return []  
   # If the length of list=1, return that element 
   if len[list1] == 1:  
       return [list1]  
   l = []  
   for i in range[len[list1]]:  
       m = list1[i]  
      # Extract list1[i] or m from the list. remlist1 is  
      # remaining list  
       remlist1 = list1[:i] + list1[i+1:]  
      # Generating all permutations where m is first  
      # element  
       for p in permutation[remlist1]:  
            l.append[[m] + p]  
   return l 
if __name__=="__main__": 
   print[list[permutation[[1,2,3,4]]]] 

Output- 
[[1, 2, 3, 4], [1, 2, 4, 3], [1, 3, 2, 4], [1, 3, 4, 2], [1, 4, 2, 3], [1, 4, 3, 2], [2, 1, 3, 4], [2, 1, 4, 3], [2, 3, 1, 4], [2, 3, 4, 1], [2, 4, 1, 3], [2, 4, 3, 1], [3, 1, 2, 4], [3, 1, 4, 2], [3, 2, 1, 4], [3, 2, 4, 1], [3, 4, 1, 2], [3, 4, 2, 1], [4, 1, 2, 3], [4, 1, 3, 2], [4, 2, 1, 3], [4, 2, 3, 1], [4, 3, 1, 2], [4, 3, 2, 1]] 

Must Read

  • How to Convert String to Lowercase in
  • How to Calculate Square Root
  • User Input | Input [] Function | Keyboard Input
  • Best Book to Learn Python

Conclusion

There are some use cases or problem statements when we need to find all the possible orders in which elements can be arranged. So we use permutations from itertools. Some people get confused between combinations and python permutation, in permutations the order matters but in combinations, the order doesn’t matter. 

What is permutation function in Python?

A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Examples: Input : str = 'ABC' Output : ABC ACB BAC BCA CAB CBA.

How do you write a permutation formula in Python?

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}.

How do you run a permutation in Python?

First import itertools package to implement the permutations method in python. This method takes a list as an input and returns an object list of tuples that contain all permutations in a list form.

How do you do permutations in Python without Itertools?

A. To create combinations without using itertools, iterate the list one by one and fix the first element of the list and make combinations with the remaining list. Similarly, iterate with all the list elements one by one by recursion of the remaining list.

Chủ Đề