码迷,mamicode.com
首页 > 其他好文 > 详细

【Checkio Exercise】Probably Dice

时间:2018-06-24 17:03:54      阅读:374      评论:0      收藏:0      [点我收藏+]

标签:fun   tput   nes   func   rom   ice   its   code   range   

题目:

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 Exercise】Probably Dice

标签:fun   tput   nes   func   rom   ice   its   code   range   

原文地址:https://www.cnblogs.com/bladeofstalin/p/9220767.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!