码迷,mamicode.com
首页 > 编程语言 > 详细

python 扔骰子

时间:2017-04-24 21:21:47      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:ima   pre   pop   weight   family   get   iter   put   else   

把一个骰子扔n次, n次朝上一面的点数和为s。
输入n, 打印出s的所有可能的值出现的概率。
 1 from decimal import Decimal
 2 
 3 def get_dice():
 4     # 一个骰子扔n次
 5     times = input(please input an integer\n)
 6     # 默认点数
 7     number = [1, 2, 3, 4, 5, 6]
 8     result = []
 9     dice = {}
10     while times > 0:
11         result.append(number)
12         times -= 1
13 
14     length = len(result)
15     # 所有可能性
16     total = len(number) ** length
17 
18     if length >= 2:
19         while length > 2:
20             temp = []
21             for i in result[-1]:
22                 for j in result[-2]:
23                     temp.append(i+j)
24             result.pop(-1)
25             result[-1] = temp
26             length -= 1
27 
28         for m in result[0]:
29             for n in result[1]:
30                 dice[m+n] = dice.setdefault(m+n, 0) + 1
31     else:
32         for i in result[0]:
33             dice[i] = 1
34 
35     for num, count in dice.iteritems():
36         dice[num] = str(Decimal(100.0*count/total).quantize(Decimal(0.000))) + %
37     return dice
38 
39 for k, v in get_dice().iteritems():
40     print k, v

 

python 扔骰子

标签:ima   pre   pop   weight   family   get   iter   put   else   

原文地址:http://www.cnblogs.com/laresh/p/6758911.html

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