Create a set of words with their characters sorted


This Python code uses a set comprehension to create a new set named sorted_chars, which contains the words from the input set words, but with their characters sorted alphabetically. Here's how the code works:

  • words = {"apple", "banana", "cherry"}: This line initializes a set named words with three string elements.
  • sorted_chars = {''.join(sorted(word)) for word in words}: This line initializes the set sorted_chars using a set comprehension.
    • for word in words: This part of the code sets up a loop that iterates through each word (string) in the words set.
    • {''.join(sorted(word))}: For each word, this part sorts the characters within the word alphabetically using the sorted() function, and then ''.join() is used to concatenate the sorted characters back into a single string.
  • print(words): This line of code prints the original set words to the console.
  • print(sorted_chars): This line of code prints the sorted_chars set to the console.

Source Code

words = {"apple", "banana", "cherry"}
sorted_chars = {''.join(sorted(word)) for word in words}
print(words)
print(sorted_chars)

Output

{'banana', 'apple', 'cherry'}
{'aaabnn', 'aelpp', 'cehrry'}

Example Programs