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
Solution 1:
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.)
Solution 2:
Example implementation ensuring a minimum distance between two occurrences of the same item:
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
Solution 3:
This routine selects and prints random choices from mylist without replacement, until all choices have been exhausted.
index = range(len(mylist))
whilelen(index) > 0:
i = random.choice(index)
print mylist[i]
index.pop(i)
Post a Comment for "Python Random.choice() Function - How To Never Have Two Choices In A Row Or Close To One Another"