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 == 1seq[-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).

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]
``````

``````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)
``````

Try z=[a,b,c,d]

Then for each element e in z, do seq.append(e[randint(0,Len(e))]), e.g.

``````from random import randint

a=[1,2,3]
b=[4,5,6]
z=[a,b]
print(a[randint(0,len(a))])
f=[]
for e in z:
f.append(e[randint(0,len(e))])
print(f)
``````

Or you could use a for loop instead of a for each and use a manual counter so you could have seq[counter]=...

This will not pick the groups randomly though.

Top