Permutation of string in Python
In this post, you will learn how to calculate the permutation of a given string in different ways using Python.
In mathematics, a permutation is an arrangement of the number so that a particular set can be arranged. It is used for the list of data where the order of the data matters.
Using the itertools module
We can easily get the permutation of a string using the itertools module. For this, first we need to import the itertools module. This module provides an inbuilt method permutations() that takes a list as an input and returns an object list of tuples that contain all permutations. In the given example, we are finding the permutation of a string.
from itertools import permutations
words = [''.join(p) for p in permutations('etp')]
print(words)
Output of the above code:
['etp', 'ept', 'tep', 'tpe', 'pet', 'pte']
Using the recursion method
Recursion function is a function which is called by itself. In the given example, we call the recursion function to find the permutation of the given string. A recursion function continues until some condition is met to prevent it. That's why we use the if else statement to break the infinite recursion.
string = "abc"
# Getting all permutation
perm_result = []
def permute(st, i, length):
if i == length:
perm_result.append(''.join(st) )
else:
for j in range(i, length):
# swapping char
st[i], st[j] = st[j], st[i]
permute(st, i + 1, length)
st[i], st[j] = st[j], st[i]
permute(list(string), 0, len(string))
# Printing result
print("Permutations: ", str(perm_result))
Output of the above code:
Permutations: ['abc', 'acb', 'bac', 'bca', 'cba', 'cab']
Related Articles
Python program for insertion sort
Merge sort program in Python
Selection sort program in Python
Bubble sort program in Python
Power of a number using recursion in Python
Python dict inside list
Pandas string to datetime
Convert Excel to CSV Python Pandas
Python add list to list
Python Pandas Dataframe to CSV
Python compare two lists
Remove element from list Python
Python iterate list with index
Python program to sum all the numbers in a list
Python print without newline
Python iterate list with index
Python add list to list
Python convert xml to dict
Python dict inside list
Python convert dict to xml
Python weather api
Python raise keyword