In [2]:
import os
import numpy as np
import glob
import csv
import random

test_array = np.repeat(np.arange(6), 12)
print(test_array)


[0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3
 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5]

In [40]:
np.random.shuffle(test_array)

flag = np.hstack(([False], test_array[:-1] == test_array[1:]))
flag_array = test_array[flag]
num_ocurrences = np.sum(test_array[:-1] == test_array[1:])

print(flag_array, num_ocurrences)

np.random.shuffle(flag_array)
test_array[flag] = flag_array
num_ocurrences = np.sum(test_array[:-1] == test_array[1:])

print(flag_array, num_ocurrences)


[2 1 0 5 3 4 0 0 0] 9
[0 5 0 2 3 4 0 0 1] 7

In [51]:
# Returns a randomized version of the array where there are no consecutive numbers that are equal.
def no_repetition_randomizer(array):
    
    """Returns a randomized version of the array where there are no consecutive numbers that are equal."""
    
    np.random.shuffle(array)
    
    # Check if any two consecutive numbers are the same.
    num_ocurrences = np.sum(array[:-1] == array[1:])
    
    # While there are any ocurrences of this...
    while num_ocurrences!=0:
        
        # ...shuffle the array...
        np.random.shuffle(array)
        
        # ...create a flag for ocurrences...
        flag = np.hstack(([False], array[:-1] == array[1:]))
        flag_array = array[flag]
        
        # ...and shuffle them.
        np.random.shuffle(flag_array)
        
        # Then re-assign them to the original array...
        array[flag] = flag_array
        
        # ...and check the number of ocurrences again
        num_ocurrences = np.sum(array[:-1] == array[1:])
        
    return array

In [53]:
labels = no_repetition_randomizer(test_array)
print(labels)
help(no_repetition_randomizer)


[5 2 3 0 4 2 3 0 3 1 0 3 0 3 2 0 1 4 3 5 1 4 1 5 2 3 4 1 0 3 0 4 0 2 4 5 3
 1 0 2 0 1 0 5 4 0 5 0 5 2 0 4 2 1 0 4 1 4 5 0 1 5 0 5 0 5 0 2 4 3 2 0]
Help on function no_repetition_randomizer in module __main__:

no_repetition_randomizer(array)
    Returns a randomized version of the array where there are no consecutive numbers that are equal.


In [ ]: