Thursday, April 1, 2021

Published April 01, 2021 by Anonymous with 0 comment

Generate all possible permutations of words in a Sentence

Generate all possible permutations of words in a Sentence

Given a string S, the task is to print permutations of all words in a sentence.

Examples:

Input: S = “sky is blue”
Output:  
sky is blue
sky blue is
is sky blue
is blue sky
blue sky is
blue is sky

Input: S =” Do what you love”
Output:
Do what you love
Do what love you
Do you what love
Do you love what
Do love what you
Do love you what
what Do you love
what Do love you
what you Do love
what you love Do
what love Do you
what love you Do
you Do what love
you Do love what
you what Do love
you what love Do
you love Do what
you love what Do
love Do what you
love Do you what
love what Do you
love what you Do
love you Do what
love you what Do

Approach: The given problem can be solved using recursion. Follow the steps below to solve the problem:

  1. Traverse the sentence and split the words present in the sentence by spaces using split() and store them in a list.
  2. Permute the list using built-in python functions itertools.permutations().
  3. Traverse the permutations and convert each permutation to a list.
  4. Print these lists.

Below is the implementation of the above approach:

Python3

  

from itertools import permutations

  

  

def calculatePermutations(sentence):

  

    

    lis = list(sentence.split())

  

    

    

    permute = permutations(lis)

  

    

    for i in permute:

        

        

        

        permutelist = list(i)

          

        

        

        for j in permutelist:

            print(j, end = " ")

              

        

        print()

  

  

if __name__ == '__main__':

  

    sentence = "sky is blue"

    calculatePermutations(sentence)

Output:
sky is blue 
sky blue is 
is sky blue 
is blue sky 
blue sky is 
blue is sky

Time Complexity: O(N!), where N denotes the number of words in a sentence.
Auxiliary Space: O(N!)


Let's block ads! (Why?)


Original page link

Best Cool Tech Gadgets

Top favorite technology gadgets
      edit

0 comments:

Post a Comment