Create a set of words with their characters repeated three times from a list of words
This Python code uses a set comprehension to create a set named tripled_chars, which contains words from the words list with each character repeated three times. Here's how the code works:
- tripled_chars = {''.join([char*3 for char in word]) for word in words}: This line initializes the set tripled_chars using a set comprehension.
- for word in words: This part of the code iterates through each word in the words list.
- ''.join([char*3 for char in word]): It repeats each character in the current word three times and joins them together using an empty string. This creates the word with tripled characters.
- print(words): This line of code prints the original list of words, which is ["apple", "banana", "cherry"], to the console.
- print(tripled_chars): This line of code prints the tripled_chars set, which contains words with each character repeated three times, to the console.
Source Code
words = ["apple", "banana", "cherry"]
tripled_chars = {''.join([char*3 for char in word]) for word in words}
print(words)
print(tripled_chars)
Output
['apple', 'banana', 'cherry']
{'bbbaaannnaaannnaaa', 'aaappppppllleee', 'ccchhheeerrrrrryyy'}