Create a set of words with their characters shuffled from a list of words
This Python code shuffles the characters within each word in the words list using random sampling and creates a set named shuffled_chars to store the shuffled versions of the words. Here's how the code works:
- import random: This line imports the random module, which provides functions for generating random numbers and performing random operations.
- words = ["apple", "banana", "cherry"]: This line initializes a variable named words and assigns it a list of three words.
- shuffled_chars = {''.join(random.sample(word, len(word))) for word in words}: This line initializes a set named shuffled_chars using a set comprehension.
- for word in words: This part of the code iterates through each word in the words list.
- random.sample(word, len(word)) : For each word, it uses the random.sample function to shuffle its characters. random.sample returns a random sample from the input sequence (in this case, the characters of the word) of the specified length.
- ''.join(...): This part of the code joins the shuffled characters back together into a single string.
- print(words): This line of code prints the original words list to the console.
- print(shuffled_chars): This line of code prints the shuffled_chars set (which contains shuffled versions of the words) to the console.
Source Code
import random
words = ["apple", "banana", "cherry"]
shuffled_chars = {''.join(random.sample(word, len(word))) for word in words}
print(words)
print(shuffled_chars)
Output
['apple', 'banana', 'cherry']
{'hreyrc', 'nbaana', 'lepap'}