Checkio ExerciseProbably Dice

Posted bladeofstalin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Checkio ExerciseProbably Dice相关的知识,希望对你有一定的参考价值。

题目:

Probably Dice

Battle is full of randomnesses. You should observe randomness in a controlled setting to prepare for this inevitability. We‘ll start by rolling the dice.

Typically, when using multiple dice, you simply roll them and sum up all the result. To get started with your investigation of dice probability, write a function that takes the number of dice, the number of sides per die and a target number and returns the probability of getting a total roll of exactly the target value. The result should be given with four digits precision as ±0.0001. For example, if you roll 2 six-sided dice, the probability of getting exactly a 3 is 2/36 or 5.56%, which you should return as ≈0.0556.

技术分享图片

For each test, assume all the dice are the same and are numbered from 1 to the number of sides, inclusive. So a 4-sided die (D4) would have an equal chance of rolling a 1, 2, 3 or 4. A 20-sided die (D20) would have an equal chance of rolling any number from 1 to 20.

Tips: Be careful if you want to use a brute-force solution -- you could have a very, very long wait for edge cases.

Input: Three arguments. The number of dice, the number of sides per die and the target number as integers.

Output: The probability of getting exactly target number on a single roll of the given dice as a float.

我的解法:

 1 # -*- coding: utf-8 -*-
 2 from collections import Counter
 3 
 4 
 5 #一个骰子出现点数的可能集
 6 def probability1(size):
 7     pro = [i + 1 for i in range(size)]
 8     return pro
 9 
10 
11 # print(probability(6))
12 
13 
14 #求n个骰子出现点数的可能集
15 def probability_dice(dice_num, size):
16     pro1 = probability1(size)
17     pro3 = [x + y for x in pro1 for y in pro1]
18     for i in range(dice_num - 2):
19         pro3 = [x + y for x in pro1 for y in pro3]
20     return pro3
21 
22 # probability_dice(2,6)
23 
24 
25 def probability(dice_num, size, number):
26     gen = probability_dice(dice_num, size)
27     count1 = Counter(gen)
28     prob_num = count1[number]/len(gen)
29     prob_num = round(prob_num, 4)
30     return prob_num

问题:循环次数过多,最后一个测试是(10,10,50),运行出的结果list长度为10^10,程序跑不动了,需要进一步优化算法

 

以上是关于Checkio ExerciseProbably Dice的主要内容,如果未能解决你的问题,请参考以下文章

Python 游戏人生

几个好玩的编程游戏网站

推荐一个娱乐化学习python的网站

netcore在Linux后台运行at Interop.ThrowExceptionForIoErrno

netcore在Linux后台运行at Interop.ThrowExceptionForIoErrno

Python识别字符串集中的后缀