Python Tutorials

Python Programs

Python Compute all the Permutations of the String


Python Compute all the Permutations of the String

In this tutorial, we will learn how to compute all the permutations of a string in Python. We will cover the basic concept of permutations and use the itertools library to generate all possible permutations of a given string.


What are Permutations

Permutations are all possible arrangements of a set of elements. For a given string, permutations are all possible ways to rearrange its characters.


Syntax

The syntax to compute all the permutations of a string in Python is:

from itertools import permutations

def compute_permutations(s):
    return [''.join(p) for p in permutations(s)]


Computing all permutations of a string

We can create a function to compute all permutations of a given string using the itertools library.

For example,

  1. Import the permutations function from the itertools library.
  2. Define a function named compute_permutations that takes one parameter s.
  3. Use the permutations function to generate all possible permutations of the string.
  4. Join each permutation tuple into a string.
  5. Return a list of all permutations.
  6. Call the function with a sample string and print the result.

Python Program

from itertools import permutations

def compute_permutations(s):
    return [''.join(p) for p in permutations(s)]

# Sample string
sample_string = 'abc'

# Compute all permutations of the sample string
result = compute_permutations(sample_string)

# Print the result
print('Permutations of', sample_string, 'are:', result)

Output

Permutations of abc are: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']