Create a set of words with their characters sorted in descending order


This Python code uses a set comprehension to create a set named sorted_descending, which contains the letters of each word in the list words sorted in descending order (in reverse alphabetical order). Here's how the code works:

  • sorted_descending = {''.join(sorted(word, reverse=True)) for word in words}: This line initializes the set sorted_descending using a set comprehension.
    • for word in words: This part of the code iterates through each word in the list words.
    • ''.join(sorted(word, reverse=True)): For each word, it sorts the letters in reverse alphabetical order (descending order) using the sorted function with the reverse=True argument and then joins them back together into a single string.
  • print(words): This line of code prints the original list of words, which is ["apple", "banana", "cherry"], to the console.
  • print(sorted_descending): This line of code prints the sorted_descending set, which contains the letters of each word sorted in descending order, to the console.

Source Code

words = ["apple", "banana", "cherry"]
sorted_descending = {''.join(sorted(word, reverse=True)) for word in words}
print(words)
print(sorted_descending)

Output

['apple', 'banana', 'cherry']
{'pplea', 'yrrhec', 'nnbaaa'}

Example Programs