Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Generate all possible permutations of words in a Sentence
When it is required to generate all possible permutations of words in a sentence, Python's itertools.permutations() function provides an efficient solution. This function takes a list of words and returns all possible arrangements.
Using itertools.permutations()
The permutations() function from the itertools module generates all possible orderings of the input elements ?
from itertools import permutations
def calculate_permutations(my_string):
word_list = list(my_string.split())
permutes = permutations(word_list)
for perm in permutes:
permute_list = list(perm)
sentence = ' '.join(permute_list)
print(sentence)
my_string = "hi there"
print("The string is:")
print(my_string)
print("All possible permutations are:")
calculate_permutations(my_string)
The string is: hi there All possible permutations are: hi there there hi
More Complex Example
Let's see how it works with more words in a sentence ?
from itertools import permutations
def generate_sentence_permutations(sentence):
words = sentence.split()
perms = permutations(words)
print(f"Original sentence: {sentence}")
print(f"Total permutations: {len(list(permutations(words)))}")
print("All permutations:")
for perm in permutations(words):
print(' '.join(perm))
sentence = "I love Python"
generate_sentence_permutations(sentence)
Original sentence: I love Python Total permutations: 6 All permutations: I love Python I Python love love I Python love Python I Python I love Python love I
How It Works
The
split()method converts the sentence into a list of wordsThe
permutations()function generates all possible arrangementsEach permutation is converted back to a sentence using
join()For n words, there are n! (factorial) total permutations
Storing Permutations in a List
You can also store all permutations in a list for further processing ?
from itertools import permutations
def get_all_permutations(sentence):
words = sentence.split()
perms = permutations(words)
result = []
for perm in perms:
result.append(' '.join(perm))
return result
sentence = "good morning"
all_perms = get_all_permutations(sentence)
print(f"Sentence: {sentence}")
print(f"Permutations: {all_perms}")
Sentence: good morning Permutations: ['good morning', 'morning good']
Conclusion
Python's itertools.permutations() makes generating word permutations simple and efficient. Split the sentence into words, apply permutations, and join them back to create all possible sentence arrangements.
