Table of Contents
In this example, you will learn to compute all the permutation of the string.
To understand this example, you should have the knowledge of the following Python programming topics:
Permutation is the method of selecting elements from a set in different ways.
For example: the number of ways in which characters from yup
can be selected are yup
, ypu
, uyp
, upy
, puy
, pyu
, and not selecting any.
We will perform the same in the following examples.
1. Example 1: Using recursion
def get_permutation(string, i=0): if i == len(string): print("".join(string)) for j in range(i, len(string)): words = # swap words[i], words[j] = words[j], words[i] get_permutation(words, i + 1) print(get_permutation('yup'))
Output
yup ypu uyp upy puy pyu None
In this example, recursion is used to find the permutations of a string yup
.
- The if condition prints
string
passed as argument if it is equal to the length ofyub
. - In each iteration of the for loop, each character of
yup
is stored inwords
. - The elements of words are swapped. In this way, we achieve all different combinations of characters.
- This process continues until the maximum length is reached.
2. Example 2: Using itertools
from itertools import permutations words = [''.join(p) for p in permutations('pro')] print(words)
Output
['pro', 'por', 'rpo', 'rop', 'opr', 'orp']
Using permutations from itertools
module, we can find the permutations of a string.
Related posts:
JavaScript Methods of RegExp and String
Python Program to Compute the Power of a Number
Python Program to Print Colored Text to the Terminal
Python *args and **kwargs
Python Program to Measure the Elapsed Time in Python
Python print()
Python Set symmetric_difference()
Python Program to Display the multiplication Table
Python Set difference_update()
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python id()
Python Type Conversion and Type Casting
Python String format()
Python List sort()
Python RegEx
Python Shallow Copy and Deep Copy
Python Modules
Python Program to Find the Sum of Natural Numbers
Python issubclass()
Python map()
Python List index()
Python Program to Solve Quadratic Equation
Python Program to Print all Prime Numbers in an Interval
Python Program to Remove Punctuations From a String
Python frozenset()
Python Program to Represent enum
Python Program to Find the Size (Resolution) of a Image
Python Program to Reverse a Number
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Java – String to Reader
Python any()