iter工具创建一个列表并计算概率

2024-09-29 01:32:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我在计算“苏茜”赢得比赛的概率。在

“苏茜”赢得比赛的概率=0.837
“鲍勃”赢得比赛的概率=0.163

如果第一个赢得n场比赛的人赢了一场比赛,那么n的最小值是多少,使得Susie赢得比赛的机会大于0.9?在

到目前为止,我有这个代码:

import itertools

W = 0.837
L = 0.163
for product in itertools.product(['W','L'], repeat=3): #3=number of games
    print product

哪个打印:

^{pr2}$

然后我想用这些结果来计算“苏茜”赢得比赛的概率。在

我已经在纸上解决了这个问题,打得越多,“苏茜”赢得比赛的机会就越大。在


Tags: of代码inimportnumberforproduct概率
3条回答

我对@desired_login的观点很感兴趣,但我想我应该尝试计算排列,而不是迭代它们:

import sys
if sys.hexversion >= 0x3000000:
    rng = range     # Python 3.x
else:
    rng = xrange    # Python 2.x

def P(n, k):
    """
    Calculate permutations of (n choose k) items
    """
    if 2*k > n:
        k = n - k
    res = 1
    for i in rng(k):
        res = res * (n-i) // (i+1)
    return res

Ps = 0.837    # Probability of Susie winning one match
Px = 0.980    # Target probability

# Probability of Susie winning exactly k of n matches
win_k         = lambda n,k: P(n, k) * Ps**k * (1.0-Ps)**(n-k)
# Probability of Susie winning k or more of n matches
win_k_or_more = lambda n,k: sum(win_k(n, i) for i in rng(k, n+1))

def main():
    # Find lowest k such that the probability of Susie winning k or more of 2*k - 1 matches is at least Px
    k = 0
    while True:
        k += 1
        n = 2*k - 1
        prob = win_k_or_more(n, k)
        print('Susie wins {} or more of {} matches: {}'.format(k, n, prob))
        if prob >= Px:
            print('At first to {} wins, Susie has >= {} chance of winning the match.'.format(k, Px))
            break

if __name__=="__main__":
    main()

对于Px=0.98,这将导致

^{pr2}$

对于这个算法,运行时类似于O(n^3),而对于其他算法则是O(2^n)。在

您可以使用字典来计算概率:

import itertools
import operator

probabilities = {'W':0.837, 'L':0.163}

for product in itertools.product(['W','L'], repeat=3): #3=number of games
    p = reduce(operator.mul,
               [probabilities[p] for p in product])
    print product, ":", p

^{}函数使用第一个参数中给定的函数累加列表中的所有元素—这里我们通过乘法来累加它们。在

这将给出每个事件序列的概率。从中你可以很容易地选择哪一个是“苏茜赢了一场比赛”,并求出概率的总和。这样做的一种可能性是:

^{pr2}$

这个条件只适用于3游戏,但我真的把这个留给你-很容易将它推广到n游戏:)

您还需要循环n的值。还要注意,“first to n”与“best out 2n-1”相同。所以我们可以说m = 2 * n - 1,看看谁在这一盘中赢的最多。max(set(product), key=product.count)是一种简短但不透明的方法,可以判断谁赢得了最多的比赛。另外,既然可以直接将值存储在元组中,为什么还要费心用字符串来表示概率,然后使用字典来读取它们呢。在

import itertools

pWin = 0 #the probability susie wins the match
n = 0
while pWin<0.9:
    n += 1
    m = 2 * n - 1
    pWin = 0
    for prod in itertools.product([0.837,0.163], repeat=m):
        #test who wins the match
        if max(set(prod), key=prod.count) == 0.837:
            pWin += reduce(lambda total,current: total * current, prod)
print '{} probability that Susie wins the match, with {} games'.format(pWin, n)

相关问题 更多 >