骰子期望 拼多多[编程题](python AC解)

骰子期望 拼多多[编程题](python AC解)_第1张图片
思路都写在注释里了

n = int(input())
x = input().split(' ')
res = []
maxlen = 0
for each in x:
    this_x = int(each)
    maxlen = max(maxlen,this_x)
    tempres = [(1/this_x) for _ in range(this_x)]
    res.append(tempres)
for i in range(len(res)):
    while len(res[i]) < maxlen:#假设最大的xi为maxlen,我们将每一个不到maxlen的数组都填充0到maxlen的长度
        res[i].append(0)#res[i][j]代表res[i]这个骰子,摇到j+1的概率(因为list索引从0开始)
#print(res)
p_dict = {}#max_val:p

#摇到的最大值是val的概率是
#所有都摇到[1,val]的概率(下面的p_left)-所有都摇到[1,val-1]的概率(下面的p_right)
for i in range(maxlen,0,-1):
    this_val = i
    p_left = 1
    for j in range(n):
        p_left = p_left*sum(res[j][:i])
    p_right = 1
    for j in range(n):
        p_right = p_right*sum(res[j][:i-1])
    p_dict[this_val] = p_left-p_right
res_1 = 1
#对摇到1单独处理
for j in range(n):
    res_1 = res_1 * res[j][0]
p_dict[1] = res_1
final_res = 0
for each_val in p_dict:
    final_res += p_dict[each_val]*each_val
print('%.2f'%final_res)#,res,maxlen,p_dict)

你可能感兴趣的:(leetcode,python编程技巧)