I was given a list of words let’s say about 200 different words. And I'm meant to create a code that generates 3 random words each together.
For example: wordlist = ["a", "b", "c", "d", "e", ..., "z"]
The Output should be:
"a", "d", "z"
"c", "o", "x"
"f", "s", "a"
- and so on
CodePudding user response:
import random
wordlist = ["a","b","c","d","e","f","g"]
print(random.sample(wordlist, 3))
CodePudding user response:
If the words in each set of 3 cannot be reused in another set, you will need to shuffle the whole list of words before making the sets. The shuffle function from the random module can do the shuffling and you can pick sets of 3 words sequentially from the shuffled list of words (using zip in my example below)
wordlist = ["a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x","y","z"]
from random import shuffle
shuffle(wordlist)
trigrams = [t for t in zip(*[iter(wordlist)]*3)]
print(*trigrams,sep="\n")
('w', 'n', 's')
('e', 't', 'b')
('c', 'r', 'z')
('j', 'l', 'g')
('a', 'd', 'm')
('i', 'h', 'y')
('k', 'p', 'f')
('q', 'u', 'v')
Note that two letters (words) haven't been used because there are only 26 letters and one more would have been needed to get a 9th set.