The Wayback Machine - https://web.archive.org/web/20240927100855/https://www.geeksforgeeks.org/python-permutation-given-string-using-inbuilt-function/
Open In App

Python | Permutation of a given string using inbuilt function

Last Updated : 07 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

We have existing solution for this problem please refer Permutations of a given string using STL link. We can also solve this problem in python using inbuilt function permutations(iterable). 

Python3




# Function to find permutations of a given string
from itertools import permutations
 
def allPermutations(str):
      
     # Get all permutations of string 'ABC'
     permList = permutations(str)
 
     # print all permutations
     for perm in list(permList):
         print (''.join(perm))
       
# Driver program
if __name__ == "__main__":
    str = 'ABC'
    allPermutations(str)


Output:

ABC
ACB
BAC
BCA
CAB
CBA

Permutation and Combination in Python Permutations of a given string with repeating characters The idea is to use dictionary to avoid printing duplicates. 

Python3




from itertools import permutations
import string
 
s = "GEEK"
a = string.ascii_letters
p = permutations(s)
 
# Create a dictionary
d = []
for i in list(p):
 
    # Print only if not in dictionary
    if (i not in d):
        d.append(i)
        print(''.join(i))


Output:

GEEK
GEKE
GKEE
EGEK
EGKE
EEGK
EEKG
EKGE
EKEG
KGEE
KEGE
KEEG

Time Complexity: O(n!) where n is the size of the string.
Auxiliary Space: O(n!) 

Approach: Using Recursion

This code generates all possible permutations of a given string using recursion.

Algorithm

1. Take input string from the user
2. Define a recursive function to generate all possible permutations of the given string
3. Base case: If the length of the input string is 1, return the string
4. Recursive case: For each character in the string, fix it and recursively find all the permutations of the remaining characters
5. Combine the fixed character with each of the permutations obtained from the recursive call and append it to the list of permutations
6. Return the list of permutations

Python3




def generate_permutations(string):
    if len(string) == 1:
        return [string]
 
    permutations = []
    for i in range(len(string)):
        fixed_char = string[i]
        remaining_chars = string[:i] + string[i+1:]
        for perm in generate_permutations(remaining_chars):
            permutations.append(fixed_char + perm)
 
    return permutations
 
string ='GEEK'
 
permutations_list = generate_permutations(string)
z=set(permutations_list)
 
for perm in z:
    print(perm)


Output

GKEE
KEEG
KEGE
KGEE
EKGE
EGEK
EEGK
GEKE
EGKE
EKEG
GEEK
EEKG

Time complexity: O(n*n!), where n is the length of the input string.

Auxiliary Space: O(n*n!).



Similar Reads

Histogram Plotting and stretching in Python (without using inbuilt function)
Prerequisites: OpenCV Python Program to analyze an image using Histogram Histogram of a digital image with intensity levels in the range of 0 to L-1 is a discrete function - h(rk) = nk where rk = kth intensity value and no = number of pixels in the image with rk intensity value. If the image has M rows and N columns, then the total number of pixels
3 min read
MoviePy – Displaying a Frame of Video Clip using inbuilt display method
In this article we will see how we can show a single frame at given time of the video file clip in MoviePy using inbuilt display method. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF's. Video is formed by the frames, combination of frames creates a video each frame is an individual image. We
2 min read
Inbuilt Data Structures in Python
Python has four non-primitive inbuilt data structures namely Lists, Dictionary, Tuple and Set. These almost cover 80% of the our real world data structures. This article will cover the above mentioned topics. Above mentioned topics are divided into four sections below. Lists: Lists in Python are one of the most versatile collection object types ava
3 min read
Arcade inbuilt functions to draw polygon in Python3
The arcade library is a high-tech Python Package with advanced set of tools for making 2D games with gripping graphics and sound. It is Object-oriented and is especially built for Python 3.6 and above versions. Arcade has two inbuilt functions for drawing a polygon: 1. arcade.draw_polygon_outline( ) : This function is used to draw the outline of th
2 min read
Arcade inbuilt functions to draw point(s) in Python3
The Arcade library is a modern Python Module used widely for developing 2D video games with compelling graphics and sound. Arcade is an object-oriented library. It can be installed like any other Python Package. In this article, we will learn what are the arcade inbuilt functions to draw point. Arcade library is a modern framework, which makes draw
3 min read
Permutation and Combination in Python
Python provides direct methods to find permutations and combinations of a sequence. These methods are present in itertools package. Permutation 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. C/C++ C
4 min read
SymPy | Permutation.is_Identity() in Python
Permutation.is_Identity() : is_Identity() is a sympy Python library function that checks whether the Permutation is an identity permutation. Syntax : sympy.combinatorics.permutations.Permutation.is_Identity() Return : true - if he Permutation is an identity permutation; otherwise false Code #1 : is_Identity() Example # Python code explaining # SymP
1 min read
Python | SymPy Permutation.inversion_vector()
Permutation.inversion_vector() : inversion_vector() is a sympy Python library function that returns the inversion_vector value of the permutation in argument. The inversion vector includes those elements whose value indicates the no. of elements in the permutation that are < it and lie on its right hand side. Syntax : sympy.combinatorics.permuta
2 min read
Python | SymPy Permutation.index() method
Permutation.index() : index() is a sympy Python library function that returns the index value of the permutation in argument. Index of a permutation = Sum of all subscripts j such that permutation[j] is greater than permutation[j+1]. Syntax : sympy.combinatorics.permutations.Permutation.index() Return : index value of the permutation Code #1 : inde
1 min read
Python | SymPy Permutation.get_precedence_matrix() method
Permutation.get_precedence_matrix() : get_precedence_matrix() is a sympy Python library function that calculates the precedence matrix for the permutation in argument by calculating the precedence distance between the two. p and q represent n jobs. The precedence metric counts the no. of times a job n is preceded by job m in both p and q. This is a
3 min read
Python | SymPy Permutation.get_precedence_distance() method
Permutation.get_precedence_distance() : get_precedence_distance() is a sympy Python library function that calculates the precedence distance between two permutations. p and q represent n jobs. The precedence metric counts the no. of times a job n is preceded by job m in both p and q. This is a commutative matrix. Syntax : sympy.combinatorics.permut
2 min read
Python | SymPy Permutation.get_positional_distance() method
Permutation.get_positional_distance() : get_positional_distance() is a sympy Python library function that calculates the positional distance between two permutations. Syntax : sympy.combinatorics.permutations.Permutation.get_positional_distance() Return : positional distance between two permutations Code #1 : get_positional_distance() Example # Pyt
1 min read
Python | SymPy Permutation.get_adjacency_matrix() method
Permutation.get_adjacency_matrix() : get_adjacency_matrix() is a sympy Python library function that calculates the adjacency matrix for the permutation in argument. Syntax : sympy.combinatorics.permutations.Permutation.get_adjacency_matrix() Return : calculates the adjacency matrix for the permutation Code #1 : get_adjacency_matrix() Example # Pyth
3 min read
Python | SymPy Permutation.get_adjacency_distance() method
Permutation.get_adjacency_distance() : get_adjacency_distance() is a sympy Python library function that calculates the adjacency distance between two permutations. Syntax : sympy.combinatorics.permutations.Permutation.get_adjacency_distance() Return : adjacency distance between two permutation Code #1 : get_adjacency_distance() Example # Python cod
1 min read
Python | SymPy Permutation.full_cyclic_form() method
Permutation.full_cyclic_form() : full_cyclic_form() is a sympy Python library function that returns the permutation in cyclic form, by including the singletons. Syntax : sympy.combinatorics.permutations.Permutation.full_cyclic_form() Return : permutation in cyclic form Code #1 : full_cyclic_form() Example # Python code explaining # SymPy.Permutatio
1 min read
Python | SymPy Permutation.from_sequence() method
Permutation.from_sequence() : from_sequence() is a sympy Python library function that returns the permutation which is required to obtain 'i' from the sorted elements of 'i'. A 'key' can also be passed as an argument if any custom string is required. Syntax : sympy.combinatorics.permutations.Permutation.from_sequence() Return : returns the permutat
2 min read
Python | SymPy Permutation.from_inversion_vector() method
Permutation.from_inversion_vector() : from_inversion_vector() is a sympy Python library function that returns the permutation from the inversion vector. Inversion Vector - The number of elements > ith element to the left of ith element in a permutation gives the ith element of the inversion vector. Syntax : sympy.combinatorics.permutations.Permu
2 min read
Python | SymPy Permutation.descents() method
Permutation.descents() : descents() is a sympy Python library function that returns the position of descents in the permutation. Descents are the elements where a[i] > a[i+1] Syntax : sympy.combinatorics.permutations.Permutation.descents() Return : position of descents in the permutation Code #1 : descents() Example # Python code explaining # Sy
1 min read
Python | SymPy Permutation.ascents() method
Permutation.ascents() : ascents() is a sympy Python library function that returns the position of ascents in the permutation. Ascents are the elements where a[i] < a[i+1] Syntax : sympy.combinatorics.permutations.Permutation.ascents() Return : position of ascents in the permutation Code #1 : ascents() Example # Python code explaining # SymPy.asc
1 min read
Python | SymPy Permutation.atoms() method
Permutation.atoms() : atoms() is a sympy Python library function that returns all the elements that are present in the permutation. Syntax : sympy.combinatorics.permutations.Permutation.atoms() Return : elements of the argumented permutation. Code #1 : atoms() Example # Python code explaining # SymPy.Permutation.atoms() # importing SymPy libraries
1 min read
Python | SymPy Permutation.cardinality() method
Permutation.cardinality() : cardinality() is a sympy Python library function that returns all the possible number of permutation. Syntax : sympy.combinatorics.permutations.Permutation.cardinality() Return : all the possible number of permutation Code #1 : cardinality() Example # Python code explaining # SymPy.Permutation.cardinality() # importing S
1 min read
Python | SymPy Permutation.commutator() method
Permutation.commutator() : commutator() is a sympy Python library function that returns the commutator of the partition. Suppose 'a' and 'b' are part of 'C', then the commutator of a and b is the 'C' identity iff a and b commute, i.e. ab == ba. Syntax : sympy.combinatorics.permutations.Permutation.commutator() Return : commutator of the partition C
2 min read
Python | SymPy Permutation.cycle_structure() method
Permutation.cycle_structure() : cycle_structure() is a sympy Python library function that returns the cycle structure of the permutation as a dictionary and this will indicate the multiplicity of each cycle length. Syntax : sympy.combinatorics.permutations.Permutation.cycle_structure() Return : cycle structure of the permutation as a dictionary Cod
1 min read
Python | SymPy Permutation.cyclic_form() method
Permutation.cyclic_form() : cyclic_form() is a sympy Python library function that returns the cyclic notation from the canonical notation, by omitting the singletons. Syntax : sympy.combinatorics.permutations.Permutation.cyclic_form() Return : cyclic notation from the canonical notation Code #1 : cyclic_form() Example # Python code explaining # Sym
1 min read
Python | SymPy Permutation.cycles() method
Permutation.cycles() : cycles() is a sympy Python library function that returns the number of cycles present in the permutation. This also includes the singleton. Syntax : sympy.combinatorics.permutations.Permutation.cycles() Return : number of cycles present in the permutation Code #1 : cycles() Example # Python code explaining # SymPy.Permutation
1 min read
Python | Sympy Permutation().array_form method
With the help of sympy.combinatorics.Permutation().array_form method, we can get the linear array from multidimensional array or matrix by using sympy.combinatorics.Permutation().array_form method. Syntax : sympy.combinatorics.Permutation().array_form Return : Return an array having single dimension. Example #1 : In this example we can see that by
1 min read
SymPy | Permutation.inversions() in Python
Permutation.inversions() : inversions() is a sympy Python library function that returns the number of inversions value of the permutation in the argument. The inversion vector includes those elements whose value indicates the no. of elements in the permutation that are < it and lie on its right-hand side. Syntax : Return : number of inversions v
2 min read
SymPy | Permutation.is_Empty() in Python
Permutation.is_Empty() : is_Empty() is a sympy Python library function that checks whether the permutation is a set with zero elements. Syntax : sympy.combinatorics.permutations.Permutation.is_Empty() Return : true : if empty; otherwise false Code #1 : is_Empty() Example # Python code explaining # SymPy.Permutation.is_Empty() # importing SymPy libr
1 min read
SymPy | Permutation.is_Singleton() in Python
Permutation.is_Singleton() : is_Singleton() is a sympy Python library function that checks whether the permutation contains only one single element. Syntax : sympy.combinatorics.permutations.Permutation.is_Singleton() Return : true - if permutation is having only one element; otherwise false Code #1 : is_Singleton() Example # Python code explaining
1 min read
SymPy | Permutation.is_even() in Python
Permutation.is_even() : is_even() is a sympy Python library function that checks whether the permutation is even. Syntax : sympy.combinatorics.permutations.Permutation.is_even() Return : true - if the permutation is even; otherwise false Code #1 : is_even() Example # Python code explaining # SymPy.Permutation.is_even() # importing SymPy libraries f
1 min read