欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > Study Plan For Algorithms - Part36

Study Plan For Algorithms - Part36

2024/10/25 7:20:49 来源:https://blog.csdn.net/qq_24058289/article/details/142447194  浏览:    关键词:Study Plan For Algorithms - Part36

1. n个骰子的点数
把n个骰子扔在地上,所有骰子朝上一面的点数之和为s。输入n,打印出s的所有可能的值出现的概率。
方法一:

def dicesProbability(n):maxValue = 6if n < 1:return []maxSum = maxValue * nres = [0] * (maxSum - n + 1)def helper(n, res):for i in range(1, maxValue + 1):computedSum(n, n, i, res)def computedSum(origin, current, sum, res):if current == 1:res[sum - origin] += 1else:for i in range(1, maxValue + 1):computedSum(origin, current - 1, i + sum, res)helper(n, res)total = 6 ** nratio = [res[i] / total for i in range(len(res))]return ratio

方法二:

def dicesProbability(n):maxValue = 6if n < 1:return []sumArr = [[0] * (maxValue * n + 1), [0] * (maxValue * n + 1)]temp = 0for i in range(1, maxValue + 1):sumArr[temp][i] = 1for j in range(2, n + 1):for k in range(j):sumArr[1 - temp][k] = 0for m in range(j, maxValue * j + 1):sumArr[1 - temp][m] = 0for l in range(1, min(m + 1, maxValue + 1)):sumArr[1 - temp][m] += sumArr[temp][m - l]temp = 1 - temptotal = 6 ** nratio = [sumArr[temp][i] / total for i in range(n, maxValue * n + 1)]return ratio

方法三:

def dicesProbability(n):ratio = [1/6] * 6for i in range(2, n + 1):temp = [0] * (5 * i + 1)for j in range(len(ratio)):for l in range(6):temp[j + l] += ratio[j] / 6ratio = tempreturn ratio

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com