Python random.choice () function - like never having two options in a row or close together

Say I have

mychoice = random.choice(['this is random response 1','this is random response 2', 'this is random response 3', 'and 4', 'and so on']) 

How can I avoid repeating the same choice several times in a row? Or how can I set a condition to make a certain choice, only after choosing a certain number of other options? Or is there a module more suitable for my needs in this regard?

+4
source share
3 answers

the simplest solution would probably be to build a usedQueue length of length k (where k is the number of choices before the selection is resolved.) When you select the selection, remove it from the original list and put it in usedQueue . Then, if usedQueue.length > k , put one back in your array.

As already mentioned, this greatly reduces the randomness of your algorithm. However, it has practical applications (take a look at iTunes.)

+8
source

An example implementation that provides the minimum distance between two occurrences of the same element:

 def choice_gen(choices, min_dist): last_choices = collections.deque(maxlen=min_dist) choices = set(choices) while 1: c = random.choice(list(choices - set(last_choices))) last_choices.append(c) yield c 
+2
source

This procedure selects and prints random options from the list without replacement, until all options are exhausted.

 index = range(len(mylist)) while len(index) > 0: i = random.choice(index) print mylist[i] index.pop(i) 
0
source

All Articles