【Checkio Exercise】Probably 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.

Image

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,程序跑不动了,需要进一步优化算法

 

转载于:https://www.cnblogs.com/bladeofstalin/p/9220767.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值