扔骰子
把一个骰子扔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