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


When it is required to print all the permutations of a string in lexicographic order using recursion, a method is defined, that uses the ‘for’ loop to iterate over the sequence of elements, and use the ‘join’ method to join the elements.

Below is the demonstration of the same −

Example

 Live Demo

from math import factorial
def lexicographic_permutation_order(s):
   my_sequence = list(s)
   for _ in range(factorial(len(my_sequence))):
      print(''.join(my_sequence))
      next = next_in_permutation(my_sequence)

      if next is None:
         my_sequence.reverse()
      else:
         my_sequence = next

def next_in_permutation(my_sequence):
   if len(my_sequence) == 0:
      return None
   next = next_in_permutation(my_sequence[1:])
   if next is None:
      my_sequence[1:] = reversed(my_sequence[1:])
      q = 1
      while q < len(my_sequence) and my_sequence[0] > my_sequence[q]:
         q += 1
      if q == len(my_sequence):
         return None
      my_sequence[0], my_sequence[q] = my_sequence[q], my_sequence[0]
      return my_sequence
   else:
      return [my_sequence[0]] + next

my_input = input('Enter a string : ')
print("The string is :")
print(my_input)
print("The method is being called...")
lexicographic_permutation_order(my_input)

Output

Enter a string : hey
The string is :
hey
The method is being called...
hey
hye
yeh
yhe
hey
hye

Explanation

  • The required packages are imported.

  • A method named ‘lexicographic_permutation_order’ is defined that helps find the lexicographic order of elements.

  • The method ‘next_in_permutation’ helps determine the next permutation in the string.

  • A string is entered by the user, and is displayed on the console.

  • The method is called by passing this string as a parameter.

  • The output is displayed on the console.

Updated on: 16-Apr-2021

273 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements