• 造轮子之随机函数


    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
    
    
  • 相关阅读:
    解决web网页访问慢的问题
    Django安装配置(for Mac)
    Django安装(for Mac)
    HTML5中的新事件
    关于http-equiv
    【转】@fant-face
    textarear中的value....还是...innertext
    清除浮动的元素的margin-top触碰不到,浮动元素的边界
    常用排序算法总结(一)
    JS常用特效方法总结
  • 原文地址:https://www.cnblogs.com/theodoric008/p/8759338.html
Copyright © 2020-2023  润新知