Group words with the same set of characters in Python
Grouping words with the same set of characters in Python is also known as Group Anagrams, Given a list of words with the same set of characters with different positions in word like, ‘hoop’ and ‘pooh’ and we have to group them together in a list.
Problem Statement: Grouping words with the same set of characters.
Input:
list= ['hello' ,'oellh' ,'lleho' , 'how' ,'woh','ohw' ,'hoop' ,'pooh' ,'ooph']
Output:
[['hello', 'oellh', 'lleho'], ['how', 'woh', 'ohw'], ['hoop', 'pooh', 'ooph']]
“Please refer to the following links if any concept is not explored by you!”
pre-requisite:
1.Collections Module in Python
2.All types of loops in Python with examples
3.List and Dictionary Manipulation in Python
4. String split and join in Python
#importing defaultdict method from the collections module from collections import defaultdict input_list = ['hello' ,'oellh' ,'lleho' , 'how' ,'woh','ohw' ,'hoop' ,'pooh' ,'ooph'] #when list object is passed to defaultdict then values of dictionary is list group = defaultdict(list) #looping over each word in list for word in input_list: group[str(sorted(word))].append(word) #getting similar pairs pairs = list(group.values()) #printing the results print(pairs)
Output:
[['hello', 'oellh', 'lleho'], ['how', 'woh', 'ohw'], ['hoop', 'pooh', 'ooph']]
Explanation:
- use of defaultdict method is to create a dictionary corresponding to key having characters of words.
- use of list argument is to create key-value list pairs.
- str method on sorted(word) creates a list of keys having alphabets of words.
- append(word) pairs similar words.
Python docs:
Data structure
Leave a Reply