Generate all possible permutations of words in a Sentence

Generate all possible permutations of words in a SentenceGiven a string S, the task is to print permutations of all words in a sentence.Examples:Input: S = “sky is blue”Output:  sky is bluesky blue isis sky blueis blue skyblue sky isblue is skyInput: S =” Do what you love”Output:Do what you loveDo what love youDo you what loveDo you love whatDo love what youDo love you whatwhat Do you lovewhat Do love youwhat you Do lovewhat you love Dowhat love Do youwhat love you Doyou Do what loveyou Do love whatyou what Do loveyou what love Doyou love Do whatyou love what Dolove Do what youlove Do you whatlove what Do youlove what you Dolove you Do whatlove you what DoApproach: The given problem can be solved using recursion. Follow the steps below to solve the problem:Traverse the sentence and split the words present in the sentence by spaces using split() and store them in a list.Permute the list using built-in python functions itertools.permutations().Traverse the permutations and convert each permutation to a list.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!)Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.