import random


def random_threshold_sequence(n,p,seed=None):
    """
    Create a random threshold sequence of size n.
    A creation sequence is built by randomly choosing d's with
    probabiliy p and i's with probability 1-p.

    s=nx.random_threshold_sequence(10,0.5)

    returns a threshold sequence of length 10 with equal
    probably of an i or a d at each position.

    A "random" threshold graph can be built with

    G=nx.threshold_graph(s)

    """
    if not seed is None:
        random.seed(seed)

    if not (p<=1 and p>=0):
        raise ValueError("p must be in [0,1]")

    cs=['d']  # threshold sequences always start with a d
    for i in range(1,n):
        if random.random() < p: 
            cs.append('d')
        else:
            cs.append('i')
    return cs