Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python random.choice() function - how to never have two choices in a row or close to one another

Let's 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 having the same choice being repeated more than once in a row? Or how can I can I set a condition to make a particular choice only appear after a certain number of other choices have been chosen? Or is there a module better suited to my needs in this regard?

like image 744
progrider Avatar asked Dec 28 '22 19:12

progrider


1 Answers

the simplest solution would probably be to construct a usedQueue of length k (where k is the number of selections before a choice is allowed to repeat.) When you select a choice, remove it from your original list and place it in usedQueue. Then, if usedQueue.length > k, pop one back onto your array.

As already stated, this significantly reduces the randomness of your algorithm. That said, it does have practical uses (take a look at iTunes.)

like image 162
Karmic Coder Avatar answered Dec 31 '22 14:12

Karmic Coder