Program to Obtain Permutations of a given String in Python

In the following tutorial, we will learn how we can compute all the permutations of a given string in Python. The program can be written using two methods; one using inbuilt functions and the other by using algorithmic logic.

What are Permutations?

Permutations and combinations are an important concept in mathematics. Combinations deal with choosing whereas Permutations deal with the arrangement. So our goal is to write a program that can achieve all the permutations of a given string which means our program must be able to compute all the ways in which the letters of the given string can be arranged.

To simplify our understanding of the algorithmic logic we must first write pseudo-code:

  1. Start
  2. Inputting a String
  3. Fix one of the letters and keep swapping the remaining
  4. Permute the rest of the characters
  5. Repeat Step 2
  6. Repeat the entire process until all the permutations have been generated
  7.  End

Program to Print the Permutations of a Given String

Below is the given Python code to fulfill our task:

def permute(str_param,beg,end):  
    curr = 0;    
    if(beg == end-1):  
        for curr in range(beg,end):  
            p = list(str_param)  
            temp = p[beg]  
            p[beg] = p[curr]  
            p[curr] = temp  
            temp = p[beg] 
            p[beg] = p[curr]  
            p[curr] = temp  
input_str = "XYZ" #Input String
print("The Permutations of the input string are:") 
if len(input_str)==0: #Condition incase the length of the string is zero
    print("Invalid String")
permute(input_str,0,len(input_str)) #Function Call

The program includes a “permute” function that accepts three parameters. The program makes use of the join() method. The join() method can be used to concatenate strings using a specified separator.


The Permutations of the input string are:


Leave a Reply

Your email address will not be published. Required fields are marked *