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
stringpassed as argument if it is equal to the length ofyub. - In each iteration of the for loop, each character of
yupis 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 String title()
Python Program to Differentiate Between del, remove, and pop on a List
Python Program to Check If a List is Empty
Python Program to Return Multiple Values From a Function
Python type()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python hex()
Split a String in Java
Python Program to Get Line Count of a File
Python sum()
Python Type Conversion and Type Casting
Python String lower()
Python divmod()
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Package
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Program to Count the Number of Digits Present In a Number
Python Program to Find ASCII Value of Character
Python Object Oriented Programming
Java String Conversions
Python Program to Extract Extension From the File Name
Python Program to Convert Bytes to a String
Python String encode()
Python String isidentifier()
Python Program to Display the multiplication Table
Python slice()
Python Program to Represent enum
Python Dictionary update()
Python Dictionary setdefault()
Python map()
Python Input, Output and Import
Python Program to Merge Mails