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:
Python Program to Find HCF or GCD
Python String isspace()
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python String replace()
Python isinstance()
Python Program to Make a Simple Calculator
Python String find()
Python String casefold()
Python divmod()
Python oct()
Python Set difference()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python print()
Python len()
Python Dictionary setdefault()
Convert Character Array to String in Java
Python String expandtabs()
Python String rjust()
Python open()
Python String count()
Python format()
Python String splitlines()
Python dir()
Python Set difference_update()
Python Program to Convert Decimal to Binary Using Recursion
Python Program to Merge Mails
Python bytes()
Python Operator Overloading
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Program to Check if a Key is Already Present in a Dictionary
Python Program to Check If Two Strings are Anagram
Python Program to Solve Quadratic Equation