• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

How to Get all the Permutations of String in Python using itertools?

Aniruddha Chaudhari/38040/6
CodePython

Till now I have shared many Python programming examples. I am little surprised as I missed to write about permutations even though it is very popular.

For instance, you have to accomplish 5 jobs. You can execute these jobs in any order as you find productive. To find the best order, you have to get all the possible orders of Job. By comparing all those possible orders you can choose the best one. So the ordering of the jobs here is nothing but the permutation.

Let’s see…

What is Permutation?

The permutation is nothing but the rearrangement of the elements in the set out of all possible orders.

Let’s take a string. It is a set of characters (letters).

If you have string ‘ABCD’; ‘BACD’, ‘ABDC’… are the permutations.

The number of permutation for the given set= n! (factorial of n)

– Where n is a number of elements in the given set.

In the above example, the length of the string ‘ABCD’ is 4. The number of permutation possible with this string is 4! = 24.

Getting all the Permutations of String in Python Program:

For permutations, we can use backtracking technique. But if you are using Python, we have an inbuilt module to generate all valid permutations for the given object.

In this article, I will share a simple line of code to generate all the permutations of the string.

It’s not difficult as Python is ever mean to be the easiest language to learn.

You can use an existing Python module named itertools. This module comes with function permutations(). With this function, it is pretty easy to get all the permutations of string in Python.

import itertools
print "\nPermutations of String 'ABC'\n"
for p in itertools.permutations('ABC'):
  print(p)

This code will give full-length permutations for the elements. To print all the permutations, you just need to loop over it.

The output of a program:

Output for permutations of string in Python

All the output permutations will be in lexicographic sort order.

If you look at the output you can see the last permutation is nothing but the reverse of the input string.

So, Reversing a string in Python returns output string which is one of the permutations of the given string.

If you want to get specific length permutation, you can pass the number of char in permutations function.

Here is code. It will print all the permutations for length 2.

import itertools
for p in itertools.permutations('ABCD', 2):
  print(p)

Getting Permutation as Python List: 

As we know the list is widely used and most prominent data structure in Python, you can convert all the permutation to list.

from itertools import permutations
listPerm = list(permutations(range(1, 4)))
print listPerm

Here we are using range() function to choose the set of elements to find the permutations.

Now you can try permutations of string in Python to explore further or to make some awesome thing.

  • Take the input from the user as a string and reply back with all possible permutation.
  • You can create a small game. Ask a user to predict any permutation for the given set of elements. The user possibility of chosen right permutation is 1/(n!).

Use the comment section if you want to discuss anything related to this topic.

Python Interview Questions eBook

Pythonpython string
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Mandar Kiran
    June 9, 2017 at 9:54 am

    itertools is a very good module to use. Earlier I was doing it with a manual code.

    • Reply
      Aniruddha Chaudhari
      July 12, 2017 at 4:57 pm

      Indeed!

  • Reply
    Shalini
    June 9, 2017 at 2:14 pm

    Thanks for writing this code; I was looking for this code to use in our project. It is very easy.

    • Reply
      Aniruddha Chaudhari
      July 12, 2017 at 4:58 pm

      You’re welcome!

  • Reply
    Oyelayo
    July 12, 2017 at 2:56 pm

    Keep on the good work. You are making me to love python more, even though I am a beginner

    • Reply
      Aniruddha Chaudhari
      July 12, 2017 at 4:58 pm

      Thanks mate! It motivates me.

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard