造轮子之随机函数

def rand_pick(seq=(True, False), probabilities=(0.5, 0.5)):
    """
    依概率输出seq中的某一个元素,也可以输入长度>=3的tuple
    :param seq: 需要选择的序列tuple
    :param probabilities: 序列不同元素对应的生成概率tuple
    :return:
    """
    if not isinstance(seq, tuple):
        raise (ValueError, 'first argument must be a tuple')
    if not isinstance(probabilities, tuple):
        raise (ValueError, 'second argument must be a tuple')
    if len(seq) != len(probabilities):
        raise (ValueError, '2 argument must have same length')
    if sum(probabilities) != 1:
        raise (ValueError, 'sum of probs must be 1')

    x = random.uniform(0, 1)
    cumprob = 0.0
    item = seq[0]
    for item, item_pro in zip(seq, probabilities):
        print(item, item_pro)
        cumprob += item_pro
        if x < cumprob:
            break
    return item

def rand_proceed(prob_true):
    """
    (类似rand_pick函数)
    指定输出为真的概率,依概率输出bool
    :param prob_true:输出为True的概率
    :return: True or False
    """
    if not isinstance(prob_true, float) or not (0.0 <= prob_true <= 1.0) :
        raise ValueError("input must a float between 0 and 1")
    x = random.uniform(0, 1)
    cumprob = 0.0
    item = 0
    for item, item_pro in zip([False, True], [1 - prob_true, prob_true]):
        cumprob += item_pro
        if x < cumprob:
            break
    return item

posted @ 2018-04-09 13:58  一条图图犬  阅读(148)  评论(0编辑  收藏  举报