Python Program to Print All Permutations of a String in Lexicographic Order without Recursion


When it is required to print all the permutations of a string in the lexicographic order without using recursion, a method is defined, that takes the string as the parameter. It uses a simple ‘for’ loop to iterate over the string elements and uses ‘while’ condition to check for certain constraints.

Below is the demonstration of the same −

Example

 Live Demo

from math import factorial
def lex_permutation(my_string):
for i in range(factorial(len(my_string))):
   print(''.join(my_string))
   i = len(my_string) - 1
   while i > 0 and my_string[i-1] > my_string[i]:
      i -= 1
   my_string[i:] = reversed(my_string[i:])
   if i > 0:
      q = i
      while my_string[i-1] > my_string[q]:
         q += 1
      temp_variable = my_string[i-1]
      my_string[i-1]= my_string[q]
      my_string[q]= temp_variable

my_string = 'bhd'
print("The string is ")
print(my_string)
my_string = list(my_string)
print("The string is being sorted")
my_string.sort()
lex_permutation(my_string)

Output

The string is
bhd
The string is being sorted
bdh
bhd
dbh
dhb
hbd
hdb

Explanation

  • The required packages are imported.

  • A method named ‘lex_permutation’ is defined that takes the string as a parameter.

  • It uses the factorial method and iterates through the factorial of the string.

  • The reversed string and the original string are compared.

  • A simple swapping is done.

  • Outside the method, the string is defined, and is displayed on the console.

  • It is then sorted.

  • The method is called by passing this string.

  • The output is displayed on the console.

Updated on: 16-Apr-2021

307 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements