The Wayback Machine - https://web.archive.org/web/20240917152254/https://www.geeksforgeeks.org/python-ways-to-find-all-permutation-of-a-string/
Open In App

Python | Ways to find all permutation of a string

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

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 

Python3




# Python code to demonstrate
# to find all permutation of
# a given string
 
# Initialising string
ini_str = "abc"
 
# Printing initial string
print("Initial string", ini_str)
 
# Finding all permutation
result = []
 
def permute(data, i, length):
    if i == length:
        result.append(''.join(data) )
    else:
        for j in range(i, length):
            # swap
            data[i], data[j] = data[j], data[i]
            permute(data, i + 1, length)
            data[i], data[j] = data[j], data[i] 
permute(list(ini_str), 0, len(ini_str))
 
# Printing result
print("Resultant permutations", str(result))


Output: 

Initial string abc
Resultant permutations ['abc', 'acb', 'bac', 'bca', 'cba', 'cab']

 

  
Method #2: Using itertools 
 

Python3




# Python code to demonstrate
# to find all permutation of
# a given string
 
from itertools import permutations
 
# Initialising string
ini_str = "abc"
 
# Printing initial string
print("Initial string", ini_str)
 
# Finding all permutation
permutation = [''.join(p) for p in permutations(ini_str)]
# Printing result
print("Resultant List", str(permutation))


Output: 

Initial string abc
Resultant List ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

 

 Using recursion:

Approach:

If the length of the string is 1, return a list containing the string
Otherwise, for each character in the string:
a. Fix the current character and recursively find all permutations of the remaining characters
b. Add the current character to the beginning of each permutation
c. Append the permutations to a list and return the list

Python3




def find_permutations(s):
    if len(s) == 1:
        return [s]
    else:
        perms = []
        for i, c in enumerate(s):
            for perm in find_permutations(s[:i] + s[i+1:]):
                perms.append(c + perm)
        return perms
 
s = 'abc'
print(find_permutations(s))


Output

['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

Time complexity: O(n!)
Auxiliary Space: O(n!)



Similar Reads

Python | Ways to split a string in different ways
The most common problem we have encountered in Python is splitting a string by a delimiter, But in some cases we have to split in different ways to get the answer. In this article, we will get substrings obtained by splitting string in different ways. Examples: Input : Paras_Jain_Moengage_best Output : ['Paras', 'Paras_Jain', 'Paras_Jain_Moengage',
2 min read
Python | Ways to check string contain all same characters
Given a list of strings, write a Python program to check whether each string has all the characters same or not. Given below are a few methods to check the same. Method #1: Using Naive Method [Inefficient] C/C++ Code # Python code to demonstrate # to check whether string contains # all characters same or not # Initialising string list ini_list = [
5 min read
Generate all permutation of a set in Python
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 min read
Python | Permutation of a given string using inbuilt function
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
2 min read
Find length of a string in python (6 ways)
Strings in Python are immutable sequences of Unicode code points. Given a string, we need to find its length. Examples: Input : 'abc' Output : 3 Input : 'hello world !' Output : 13 Input : ' h e l l o ' Output :14 Methods#1: Using the built-in function len. The built-in function len returns the number of items in a container. C/C++ Code # Python co
3 min read
Python | Ways to find nth occurrence of substring in a string
Given a string and a substring, write a Python program to find the nth occurrence of the string. Let's discuss a few methods to solve the given task. Get Nth occurrence of a substring in a String using regex Here, we find the index of the 'ab' character in the 4th position using the regex re.finditer() C/C++ Code import re # Initialising values ini
4 min read
Ways to extract all dictionary values | Python
While working with Python dictionaries, there can be cases in which we are just concerned about getting the values list and don't care about keys. This is yet another essential utility and solution to it should be known and discussed. Let's perform this task through certain methods. Method #1 : Using loop + keys() The first method that comes to min
3 min read
Python | Ways to remove numeric digits from given string
Given a string (may contain both characters and digits), write a Python program to remove the numeric digits from string. Let's discuss the different ways we can achieve this task. Method #1: Using join and isdigit() C/C++ Code # Python code to demonstrate # how to remove numeric digits from string # using join and isdigit # initialising string ini
6 min read
Python | Ways to convert string to json object
In this article, we will see different ways to convert string to JSON in Python this process is called serialization. JSON module provides functions for encoding (serializing) Python objects into JSON strings and decoding (deserializing) JSON strings into Python objects. Encoding (Serializing) JSON: If you have a Python object and want to convert i
3 min read
Python | Ways to sort letters of string alphabetically
Given a string of letters, write a python program to sort the given string in an alphabetical order. Example: Input : PYTHON Output : HNOPTY Input : Geeks Output : eeGksNaive Method to sort letters of string alphabetically Here we are converting the string into list and then finally sorting the entire list alphabet wise. C/C++ Code s ="GEEKSFO
2 min read
Python | Ways to remove n characters from start of given string
Given a string and a number 'n', the task is to remove a string of length 'n' from the start of the string. Let's a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python3 code to demonstrate # how to remove 'n' characters from starting # of a string # Initialising string ini_string1 = 'garg_akshat' # Initialising nu
3 min read
Python | Ways to check if given string contains only letter
Given a string, write a Python program to find whether a string contains only letters and no other keywords. Let's discuss a few methods to complete the task. Method #1: Using isalpha() method C/C++ Code # Python code to demonstrate # to find whether string contains # only letters # Initialising string ini_str = "ababababa" # Printing ini
3 min read
Python | Ways to count number of substring in string
Given a string and a substring, write a Python program to find how many numbers of substrings are there in the string (including overlapping cases). Let's discuss a few methods below. Method #1: Using re.findall() Method C/C++ Code # Python code to demonstrate # to count total number # of substring in string import re # Initialising string s = 'aba
4 min read
Python - Ways to remove multiple empty spaces from string List
Sometimes, while working with Python strings, we have a problem in which we need to perform the removal of empty spaces in Strings. The problem of filtering a single space is easier. But sometimes we are unaware of the number of spaces. This has applications in many domains. Let's discuss certain ways in which this task can be performed. Method #1
6 min read
Python | Ways to concatenate boolean to string
In Python, concatenating Booleans with strings is a common task when you want to include the truth value of a Boolean variable in a text message or output. Booleans in Python are represented by the values True and False. Given a string and a Boolean value, write a Python program to concatenate the string with a Boolean value. Example: Input: ini_st
3 min read
Python | Ways to convert list of ASCII value to string
Given a list of ASCII values, write a Python program to convert those values to their character and make a string. Given below are a few methods to solve the problem. Method #1: Using Naive Method C/C++ Code # Python code to demonstrate # conversion of list of ascii values # to string # Initialising list ini_list = [71, 101, 101, 107, 115, 102, 111
3 min read
Reverse string in Python (6 different ways)
Python string library doesn't support the in-built "reverse()" as done by other python containers like list, hence knowing other methods to reverse string can prove to be useful. This article discusses several ways to achieve it in Python. Example: Input: GeeksforgeeksOutput: skeegrofskeeGReverse a string in Python using a loopIn this example, we c
7 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
Python Program for BogoSort or Permutation Sort
BogoSort also known as permutation sort, stupid sort, slow sort, shotgun sort or monkey sort is a particularly ineffective algorithm based on generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted.(Wiki) Python Program for BogoSort or Permutation SortFor example, if bogosort is u
2 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
Practice Tags :