Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pick random items from a list while avoiding picking the same item in a row

I want to iterate through list with random values. However, I want the item that has been picked to be removed from the list for the next trial, so that I can avoid picking the same item in a row; but it should be added back again after.

please help me on showing that on this simple example. Thank you

import random
    l = [1,2,3,4,5,6,7,8]
    for i in l:
        print random.choice(l)
like image 517
Err Avatar asked Dec 19 '22 20:12

Err


1 Answers

Both work for list of non-unique elements as well:

def choice_without_repetition(lst):
    prev = None
    while True:
        i = random.randrange(len(lst))
        if i != prev:
            yield lst[i]
            prev = i

or

def choice_without_repetition(lst):
    i = 0
    while True:
        i = (i + random.randrange(1, len(lst))) % len(lst)
        yield lst[i]

Usage:

lst = [1,2,3,4,5,6,7,8]
for x in choice_without_repetition(lst):
    print x
like image 151
eumiro Avatar answered Dec 21 '22 09:12

eumiro