How to NOT repeat a random.choice when printing a piece of text in python

Question:

I have three lists in text files and I am trying to generate a four-word message randomly, choosing from the prefix and suprafix lists for the first three words and the `suffix’ file for the fourth word.

However, I want to prevent it from picking a word that was already chosen by the random.choice function.

import random

a= random.random
prefix = open('prefix.txt','r').readlines()
suprafix = open('suprafix.txt','r').readlines()
suffix = open('suffix.txt','r').readlines()
print (random.choice(prefix + suprafix), random.choice(prefix + suprafix), random.choice(prefix + suprafix), random.choice(suffix))

As you can see it chooses randomly from those two lists for three words.

Asked By: Francis Brady

||

Answers:

random.sample(pop, k) selected k items from pop without replacement. Hence:

prefix1, prefix2, prefix3 = random.sample(prefix, 3)
suprafix1, suprafix2, suprafix3 = random.sample(suprafix, 3)
suffix = random.choice(suffix)
print (prefix1 + suprafix1, prefix2 + suprafix2, prefix3 + suprafix3, suffix))
Answered By: xnx

Thankyou xnx that helped me sort out the problem by using the random.sample first then printing either of them afterwards, i might have done it the long way round but this is how i did it >

import random

a= random.random

prefix = open(‘prefix.txt’,’r’).readlines()

suprafix = open(‘suprafix.txt’,’r’).readlines()

suffix = open(‘suffix.txt’,’r’).readlines()

prefix1, prefix2, prefix3 = random.sample(prefix, 3)

suprafix1, suprafix2, suprafix3 = random.sample(suprafix, 3)

suffix = random.choice(suffix)

one = prefix1, suprafix1

two = prefix2, suprafix2

three = prefix3, suprafix3

print (random.choice(one), random.choice(two), random.choice(three), suffix)

Answered By: Francis Brady
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.