Open In App

Python | Permutation of a given string using inbuilt function

Last Updated : 07 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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
Python program to count upper and lower case characters without using inbuilt functions
Given a string that contains both upper and lower case characters in it. The task is to count a number of upper and lower case characters in it. Examples :Input : Introduction to Python Output : Lower Case characters : 18 Upper case characters : 2 Input : Welcome to GeeksforGeeks Output : Lower Case characters : 19 Upper case characters: 3Method 1:
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
Python | Ways to find all permutation of a string
Given a string, write a Python program to find out all possible permutations of a string. Let's discuss a few methods to solve the problem.Method #1: Using Naive Method C/C++ Code # Python code to demonstrate # to find all permutation of # a given string # Initialising string ini_str = "abc" # Printing initial string print("Initial s
2 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
three90RightbarBannerImg