0

我是初学者,我想知道是否有更简单的方法可以用 Python 写出来。我假设某种类型的字典,但我不明白如何写出来。几天前我在游轮上,我玩掷骰子。我想知道赔率是否正确。所以,我写了这个,但我知道有一个更简单的方法。

import random

dice2 = 0
dice3 = 0
dice4 = 0
dice5 = 0
dice6 = 0
dice7 = 0
dice8 = 0
dice9 = 0
dice10 = 0
dice11 = 0
dice12 = 0

for i in range(100000):
            dice1 = random.randint(1,6)
            dice2 = random.randint(1,6)
            number = dice1 + dice2
            #print(dice1)
            if number == 2:
                        dice2 +=1
            elif number == 3:
                        dice3 += 1
            elif number == 4:
                        dice4 += 1
            elif number == 5:
                        dice5 += 1
            elif number == 6:
                        dice6 += 1
            elif number == 7:
                        dice7 += 1
            elif number == 8:
                        dice8 += 1
            elif number == 9:
                        dice9 += 1
            elif number == 10:
                        dice10 += 1
            elif number == 11:
                        dice11 += 1
            elif number == 12:
                        dice12 += 1

total = dice2+dice3+dice4+dice5+dice6+dice7+dice8+dice9+dice10+dice11+dice12

最后,它只打印出 2-12 数字的命中百分比。

4

3 回答 3

4

我会使用Counter,因为这就是它的用途:

from random import randint
from collections import Counter

counts = Counter(randint(1, 6) + randint(1, 6) for i in range(100000))
total = sum(counts.values())
number_of_tens = counts[10]
于 2013-05-28T03:17:54.197 回答
3
from random import randint

dice = [0]*11
for i in range(100000):
    dice[randint(1,6)+randint(1,6)-2] += 1

total = sum(dice) #it is 100000, of course
for i, v in enumerate(dice, 2):
    print('{0}: {1}%'.format(i, v*100.0/total))
于 2013-05-28T03:15:31.453 回答
2
import random

def roll(n=6):
    return random.randint(1, n)

dice = dict.fromkeys(range(2, 13), 0)

for i in range(100000):
    number = roll() + roll()
    dice[number] += 1

total = float(sum(dice.values()))
for k,v in dice.items():
    print "{}, {:.2%}".format(k, v/total)
于 2013-05-28T03:19:22.780 回答