- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Print anagrams together in Python using List and Dictionary
In this tutorial, we are going to write a program which finds and prints anagrams using list and dictionary. We have different approaches to every problem. Try to write code without following the tutorial. If you are not able to generate any ideas to write logic, follow the below steps.
Algorithm
1. Initialize a list of strings. 2. Initialize an empty dictionary. 3. Iterate through the list of strings. 3.1. Sort the string and check if it is present in the dictionary as key or not. 3.1.1. If the sorted string is already present dictionary as a key then, append the original string to the key. 3.2 Else map an empty list with the sorted string as key and append the original to it. 4. Initialize an empty string. 5. Iterate through the dictionary items. 5.1. Concatenate all the values to the empty string. 6. Print the string.
Let's write the code for the above algorithm.
Example
## initializing the list of strings strings = ["apple", "orange", "grapes", "pear", "peach"] ## initializing an empty dictionary anagrams = {} ## iterating through the list of strings for string in strings: ## sorting the string key = "".join(sorted(string)) ## checking whether the key is present in dict or not if string in anagrams.keys(): ## appending the original string to the key anagrams[key].append(string) else: ## mapping an empty list to the key anagrams[key] = [] ## appending the string to the key anagrams[key].append(string) ## intializing an empty string result = "" ## iterating through the dictionary for key, value in anagrams.items(): ## appending all the values to the result result += "".join(value) + " " ## printing the result print(result)
Output
If you run the above program, you will get the following output.
apple orange grapes pear peach
Conclusion
If you have any doubts regarding the tutorial, mention them in the comment section.
Advertisements