import random


def weis_urn(n_subjects, seed=None):
    """ Create a randomization list using Wei's Urn.

    Wei's Urn weights the assignment of a new subject by adjusting the
    probability of the Bernoulli random variable used to determine the next
    group according to which group is under represented.  The adjusted
    probability is a dynamic value.

    Suppose that :math:`N_{r}` is the total number of subjects already
    randomize and :math:`N_{r0}` is the number of subjects already randomized
    that were randomized to Group 0.  The probability that the next subject
    will be randomized to Group 0 is:

    .. math::
        p_{0} = 1 - \\frac{N_{r0}}{N_{r}}

    This method is only approriate for 2 groups.

    Args:
        n_subjects: The number of subjects to randomize.
        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:
        Exact balance between groups is not guaranteed when using Wei's
        Urn, but it is usually very close to balanced.
    """

    random.seed(seed)
    group_0_count = 0.0
    groups = []
    for i in range(0, n_subjects):
        if i > 0:
            cut = 1 - group_0_count / (i + 1)
        else:
            cut = 0.5
        test = random.random()
        if test < cut:
            group = 1
        else:
            group = 2
        groups.append(group)
        if group is 1:
            group_0_count += 1
    return groups