Search code examples
pythonalgorithmrandomranking

How to randomly pick numbers from ranked groups in python, to create a list of specific length


I am trying to create a sequence of length 6 which consists of numbers randomly picked from ranked groups. The first element of the sequence has to be drawn from the first group, and the last element has to be drawn from the last group.

Let the new sequence be called "seq". Then, if

a = [1,2,3]
b = [9]
c = [5,6]
d = [11,12,4]

seq[0] in a == 1
seq[-1] in d == 1

The intermediate elements have to come from lists a,b,c,d. But, if the second element is randomly drawn from 'a', then the third one, has to be drawn either from a later 'a' element, or from b/c/d. Similarly, if the third element is drawn from 'c', then the other ones have to come from later ranks like d.The groups are ranked this way.

The number of groups given now, is arbitrary (maximum of 6 groups). The length for the sequence ( len(seq) == 6 ) is standard.

One element from each group has to be in the final sequence. Repetition of elements is not allowed. All group elements are unique (and they are always numbers in the range of 1-12).


Solution

  • you have four forced choices, then two free choices. set is a good help here.

    from random import choice
    a = [1,2,3]
    b = [9]
    c = [5,6]
    d = [11,12,4]
    
    l=a+b+c+d #ordered candidates
    
    def select():
        e=set(l)
        for s in (a,b,c,d,e,e):              # 4 forced choices and 2 frees.
            e.remove(choice(tuple(s)))       # sets have no index.
        return [x for x in l if x not in e]
    

    10 samples :

    >>> for _ in range(10) : print (select())
    [1, 9, 5, 11, 12, 4]
    [1, 3, 9, 6, 11, 4]
    [1, 3, 9, 5, 6, 12]
    [1, 2, 9, 6, 11, 4]
    [1, 2, 9, 5, 6, 4]
    [2, 9, 5, 6, 11, 4]
    [1, 2, 9, 5, 11, 12]
    [1, 3, 9, 6, 11, 12]
    [3, 9, 6, 11, 12, 4]
    [1, 2, 9, 5, 12, 4]