- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - Generate all possible permutations of words in a Sentence
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.
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)
The string is : hi there All possible permutation are : hi there there hi
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.
- All possible permutations of N lists in Python
- How to generate all permutations of a list in Python?
- How to find all possible permutations of a given string in Python?
- Count words in a sentence in Python program
- Python program to count words in a sentence
- Print all words occurring in a sentence exactly K times
- Python program to sort Palindrome Words in a Sentence
- C# program to remove all duplicates words from a given sentence
- Java program to remove all duplicates words from a given sentence
- Python - Check if given words appear together in a list of sentence