Python - Generate all possible permutations of words in a Sentence

PythonServer Side ProgrammingProgramming

When it is required to generate all possible permutations of a word in a sentence, a function is defined. This function iterates over the string and depending on the condition, the output is displayed.

Example

Below is a demonstration of the same

from itertools import permutations
def calculate_permutations(my_string):

   my_list = list(my_string.split())

   permutes = permutations(my_list)

   for i in permutes:

      permute_list = list(i)

      for j in permute_list:
         print j

      print()

my_string = "hi there"
print("The string is :")
print(my_string)
print("All possible permutation are :")
calculate_permutations(my_string)

Output

The string is :
hi there
All possible permutation are :
hi there
there hi

Explanation

  • The required packages are imported into the environment.

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

  • It is split based on empty spaces.

  • These words are converted to a list and stored in a variable.

  • It is iterated over, and is displayed on the console.

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

  • The method is called by passing the required parameter.

  • The output is displayed on the console.

raja
Published on 20-Sep-2021 11:32:29
Advertisements