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 Split a List Into Evenly Sized Chunks
Python Set isdisjoint()
Python String count()
Python Numbers, Type Conversion and Mathematics
Python Program to Differentiate Between type() and isinstance()
Python Program to Check if a Number is Odd or Even
Python String isprintable()
Python Iterators
Python List index()
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
JavaScript Methods of RegExp and String
Python Program to Get Line Count of a File
Python Program to Concatenate Two Lists
Python bin()
Reading an HTTP Response Body as a String in Java
Python Dictionary copy()
Python Program to Represent enum
Python abs()
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Python Program to Check If a String Is a Number (Float)
Count Occurrences of a Char in a String
Python String istitle()
Convert char to String in Java
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python String rstrip()
APIs in Node.js vs Python - A Comparison
Python Program to Print all Prime Numbers in an Interval
Python Set clear()
Python Program to Trim Whitespace From a String
Python String strip()
Python staticmethod()
Python Program to Convert Kilometers to Miles