Randomization constraints

Hello everyone,

I am new to PsychoPi, and I am trying to program a task switching experiment in which all of the trials are task switches. I am using Windows 10 with PsychoPi 3 installed.
I would like to make my sequence of tasks random, but also to never repeat two tasks in subsequent trials. This is what I have tried:

listok = False
doubletarget = False

task = [1,2,3]*16
random.shuffle(task)

while listok == False:
    for i in range(len(task)-1):
        if task[i+1] == task[i]:
            doubletarget = True
    if doubletarget == True:
        random.shuffle(task)
        doubletarget = False
    else:
        listok = True

This approach works for smaller lists, but my computer fails to compute this huge amount of data.
Do you have any suggestions?

Hi @thewall79, found this on stack overflow (see link below):

import random
while 1:
    choices = [1, 2, 3] * 1000

    shuffle = []

    last = ""

    while choices:
        l = choices
        if last:
            l = [x for x in l if x != last]
        if not l:
            #no valid solution
            break 
        newEl = random.choice(l)
        last = newEl
        shuffle.append(newEl)
        choices.remove(newEl)
    if not choices:
        print(shuffle)
        break

Adapted from https://stackoverflow.com/a/35784338