import itertools


def dummy_code(x, discretes):
    """Dummy code a vector of covariates x for ie regression.

    Parameters
    ----------
    x : list
        List of data. Categorical values must be integer starting at 0.
    discretes : dict{int:int}
        discretes[i] is the number of discrete categories in x[i].

    Returns
    -------
    xd : list
        Dummy coded version of x as list.

    Example
    -------
    >>> dummy_code([12.1, 3], {1:5})
    [12.1, 0, 0, 0, 1]
    # Note only 4 dummy codes since all 0s indicates cateogry 4.
    """
    if len(discretes) == 0:
        return list(x)
    def as_code(i, val):
        if i not in discretes:
            return [val]
        if float(val) != int(val):
            raise TypeError('Discrete value must be integer: {},{}'.format(x,i))
        k = discretes[i]
        if not 0 <= val < k:
            raise ValueError('Discrete value not in {0..%s}: %d.'% (k-1, val))
        r = [0]*(k-1)
        if val < k-1:
            r[int(val)] = 1
        return r
    xp = [as_code(i, val) for i, val in enumerate(x)]
    return list(itertools.chain.from_iterable(xp))