Create List without similar crossovers
<p>I am trying to build a list of length = 120, which shall include 4 numbers.
The tricky thing is that the numbers shall not appear in a row and each number should occur exactly to the same amount.</p>

<p>This is my script. </p>

<pre><code>import random
List = [1,2,3,4]
seq_CG = random.sample(List,len(List))
for i in range(121):
    randomList = random.sample(List, len(List))
    if randomList[0]!=seq_CG[-1]:
        seq_CG.append(randomList)
        i = len(seq_CG)
print List, randomList, seq_CG
</code></pre>

<p>I am pretty close. However something does not work. And maybe there is even a shorter and more random solution?</p>

<p>In the big list seq_CG i do not want that numbers appear in a row. In my example it is filled with a lot of smaller lists. However it would be even nicer to have a random list of 120 numbers with an equal distribution of each number, where numbers do not appear in a row. </p>

<p>A slightly naive approach is to have an infinite loop, then scrunch up duplicate values, using <code>islice</code> to cap the total required output, eg:</p>

<pre><code>from itertools import groupby
from random import choice

def non_repeating(values):
    if not len(values) &gt; 1:
        raise ValueError('must have more than 1 value')
    candidates = iter(lambda: choice(values), object())
    # Python 3.x -- yield from (k for k, g in groupby(candidates))
    # Python 2.x
    for k, g in groupby(candidates):
        yield k

data = [1, 2, 3, 4]
sequence = list(islice(non_repeating(data), 20))
# [3, 2, 1, 4, 1, 4, 1, 4, 2, 1, 2, 1, 4, 1, 4, 3, 2, 3, 4, 3]
# [3, 2, 3, 4, 1, 3, 1, 4, 1, 4, 2, 1, 2, 3, 2, 4, 1, 4, 2, 3]
# etc...
</code></pre>

python python-2.7 open-sesame