- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
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.
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.
- Related Articles
- 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?
- Generating all possible permutations of array in JavaScript
- Reverse all the words of sentence JavaScript
- Creating all possible unique permutations of a string in JavaScript
- 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
- Replace all occurrence of specific words in a sentence based on an array of words in JavaScript
- Generate all combinations of supplied words in JavaScript
- 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

Advertisements