- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Generate all permutation of a set in Python?
In mathematics, arranging all the members of a set into some order or sequence and if the set is already ordered, rearranging (reordering) its elements is called permutation. We can generate permutation using different technique. Below are some of them,
Python comes with dedicated module for permutations and combinations called itertools.
First import the module
>>> import itertools >>>
The permutation function allows us to get permutation of N values within a list, where order matters. For example, selection N = 2 values with [1,2,3,4] is done as follows −
Permutation (order matters): >>> print(list(itertools.permutations([1,2,3,4],2))) [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
Combination (order does not matter)
>>> print(list(itertools.combinations('1234', 2))) [('1', '2'), ('1', '3'), ('1', '4'), ('2', '3'), ('2', '4'), ('3', '4')]
Below is the implementation on a list without creating new intermediate lists.
def permute(xs, low=0): if low + 1 >= len(xs): yield xs else: for p in permute(xs, low + 1): yield p for i in range(low + 1, len(xs)): xs[low], xs[i] = xs[i], xs[low] for p in permute(xs, low + 1): yield p xs[low], xs[i] = xs[i], xs[low] for p in permute([1, 2, 3]): print (p)
[1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 2, 1] [3, 1, 2]
Method 3 Using Recursion
import copy def perm(prefix,rest): for e in rest: new_rest=copy.copy(rest) new_prefix=copy.copy(prefix) new_prefix.append(e) new_rest.remove(e) if len(new_rest) == 0: print (new_prefix + new_rest) continue perm(new_prefix,new_rest) perm(,[1, 2, 3])
[1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1]
- Generate all combinations of a specific size from a single set in PHP
- How to generate all permutations of a list in Python?
- Python - Generate all possible permutations of words in a Sentence
- Print all permutation of a string using ArrayList in Java
- C++ Program to Generate All Subsets of a Given Set in the Lexico Graphic Order
- Next Permutation in Python
- C++ Program to Generate All Pairs of Subsets Whose Union Make the Set
- Find n-th lexicographically permutation of a strings in Python
- Check if all bits of a number are set in Python
- Python program for permutation of a given string inbuilt function in python
- Permutation and Combination in Python?
- Python program to get all subsets of a given size of a set
- Permutation of a given string using the inbuilt function in Python
- Python program to get all subsets of given size of a set