Python实现概率事件输出所有可能结果

示例 事件A,B发生概率为a,b,则有 ab, a(1-b),(1-a)b,(1-a)(1-b)

那(a, b, c, .....)输出?

import copy

def one_zero(n):
    “事件发生为1,不发生为0,返回所有可能”
    if n==1:
        return ["0","1"]
    L1 = one_zero(n-1)
    L2 = copy.deepcopy(L1)
    L2.reverse()
    L1 = ["0" + l for l in L1]
    L2 = ["1" + l for l in L2]
    L = L1 + L2
    return L
#print(one_zero(3))

def all_results(list1):
    "用事件发生概率替换0,1,返回所有结果"
    L = one_zero(len(list1))
    list2 = [1] * len(L)
    for i in range(len(L)):
        num = 0
        for j in L[i]:
            if j == "1":
                list2[i] = list2[i] * list1[num]
                num += 1
            else:
                list2[i] = list2[i] * (1 -list1[num])
                num += 1
    return list2

 

你可能感兴趣的:(Python实现的算法)