python 扔骰子

來源:互聯網
上載者:User

標籤: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 -= 113 14     length = len(result)15     # 所有可能性16     total = len(number) ** length17 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] = temp26             length -= 127 28         for m in result[0]:29             for n in result[1]:30                 dice[m+n] = dice.setdefault(m+n, 0) + 131     else:32         for i in result[0]:33             dice[i] = 134 35     for num, count in dice.iteritems():36         dice[num] = str(Decimal(100.0*count/total).quantize(Decimal(‘0.000‘))) + ‘%‘37     return dice38 39 for k, v in get_dice().iteritems():40     print k, v

 

python 扔骰子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.