import random


def block(n_subjects, n_groups, block_length, seed=None):
    """ Create a randomization list using block randomization.

    Block randomization takes blocks of group labels of length `block_length`,
    shuffles them and adds them to the randomization list.  This is done to
    prevent long runs of a single group. Usually `block_length` is equal
    to 4 or 6.

    Args:
        n_subjects: The number of subjects to randomize.
        n_groups: The number of groups to randomize subjects to.
        block_length: The length of the blocks.  `block` should be equal to
            :math:`k * n_{groups}, k > 1`.
        seed: (optional) The seed to provide to the RNG.

    Returns:
        list: a list of length `n_subjects` of integers representing the
            groups each subject is assigned to.

    Notes:
        The value of `block_length` should be a multiple of `n_groups` to
        ensure proper balance.
    """

    random.seed(seed)
    block_form = []
    for i in range(0, block_length):
        # If n_groups is not a factor of block_length, there will be unbalance.
        block_form.append(i % n_groups + 1)

    count = 0
    groups = []

    while count < n_subjects:
        random.shuffle(block_form)
        groups.extend(block_form)
        count += block_length

    # If `n_subjects` is not a multiple of `block_length`, only return the
    # first `n_subjects` elements of `groups`
    return groups[:n_subjects]