I want to make a program to group words consisting of the same characters in an array, but the results don’t match when using the Python programming language
Example problem: Suppose I have 3 arrays of type string as follows:
oe1 = ["abc", "def"];
oe2 = ["asd", "cab", "fed", "eqw"];
oe3 = ["qwe", "efd", "bca"];
Note: The order of the array or the elements doesn’t matter, the important thing is that they are grouped.
Output example:
[abc, cab, bca]
[asd]
[def, fed, efd]
[eqw, qwe]
But I try to use coding like this the results are not appropriate:
oe1 = ["abc", "def"];
oe2 = ["asd", "cab", "fed", "eqw"];
oe3 = ["qwe", "efd", "bca"];
anagram_list = []
for word_1 in oe1:
for word_2 in oe2:
for word_3 in oe3:
if word_1 != word_2 != word_3 and (sorted(word_1)==sorted(word_2)==sorted(word_3)):
anagram_list.append(word_1 + word_2 + word_3)
print(anagram_list)
my output is like this:
['abccabbca', 'deffedefd']
How do I make it match the example output above?
>Solution :
Here is one way to perhaps solve your problem:
- Create a function that takes three lists of words as input and returns a list of lists of anagrams, grouped by input list.
def group_anagrams(oe1, oe2, oe3):
# Create a dictionary where the keys are the sorted version of each word
# and the values are lists of the words that have the same characters.
anagrams = {}
# Loop over each word in each input list.
for words in [oe1, oe2, oe3]:
for word in words:
# Sort the word to create a unique key for each set of anagrams.
key = ''.join(sorted(word))
# Add the word to the list of anagrams for this key.
if key in anagrams:
anagrams[key].append(word)
else:
anagrams[key] = [word]
# Return the values of the dictionary (i.e. the lists of anagrams) as a list of lists.
return anagrams.values()
- Use the function to group the anagrams in your example.
oe1 = ["abc", "def"]
oe2 = ["asd", "cab", "fed", "eqw"]
oe3 = ["qwe", "efd", "bca"]
anagram_lists = group_anagrams(oe1, oe2, oe3)
# Print the result.
for anagrams in anagram_lists:
print(anagrams)
This should output the following:
[abc, cab, bca]
[asd]
[def, fed, efd]
[eqw, qwe]
Hope this helps!