Generate a set of words that are anagrams from a list of words
This Python code uses a set comprehension to create a set named anagrams, which contains the sorted letters of each word in the list words. Here's how the code works:
- anagrams = {''.join(sorted(word)) for word in words}: This line initializes the set anagrams using a set comprehension.
- for word in words: This part of the code iterates through each word in the list words.
- ''.join(sorted(word)): For each word, it sorts the letters in alphabetical order using the sorted function and then joins them back together into a single string. This effectively creates an anagram of the word.
- print(words): This line of code prints the original list of words, which is ["apple", "banana", "elppa", "race", "care", "cherry"], to the console.
- print(anagrams): This line of code prints the anagrams set, which contains the sorted letters of each word, to the console.
Source Code
words = ["apple", "banana", "elppa", "race", "care", "cherry"]
anagrams = {''.join(sorted(word)) for word in words}
print(words)
print(anagrams)
Output
['apple', 'banana', 'elppa', 'race', 'care', 'cherry']
{'aaabnn', 'cehrry', 'aelpp', 'acer'}