How to randomly pick numbers from ranked groups in python, to create a list of specific length
Question: 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).


Answer: How about this:

    
    
    from random import choice, randint
    
    v = [[1, 2, 3],
          [9],
          [5, 6],
          [11, 12, 4]]
    
    
    def whatever(values, n=6):
        first = [choice(values[0])]
        last = [choice(values[-1])]
        seq = []
        k = 0
        while len(seq) < n -2:
            k = randint(k, len(values)-1)
            seq.append(choice(values[k]))
        return first + seq + last
    
    print whatever(v, 6)
    

