看看2 die的总和等于24 python的次数

时间:2018-01-25 04:46:24

标签: python python-3.x random

我正在创建一个代码,其中两个“特殊”模具滚动总和为24。

def is24():

    die1 = [ i for i in range(20)]
    die2 = [ i for i in range(21) if i is not 9]

    d1 = random.randrange(len(die1))
    d2 = random.randrange(len(die2))

我很困惑在下面的代码的第一行放什么,因为我一直收到错误

    if d1 + d2 == 24: return 1



trials = 100000
random.seed(15)
s = 0
for i in range(trials):
    s += is24()

print("The estimate of the probability is")
print(s/trials)

1 个答案:

答案 0 :(得分:0)

您的错误可能与向int添加None有关。这是因为函数默认返回None,只要if语句失败,就会发生这种情况。试试这个:

import random


def is24():
    """Return 1 if the target is met."""
    die1 = [ i for i in range(20)]
    die2 = [ i for i in range(21) if i is not 9]

    d1 = random.randrange(len(die1))
    d2 = random.randrange(len(die2))

    if d1 + d2 == 24: 
        return 1
    return 0                                   # include this


trials = 100000
random.seed(15)
s = 0
for i in range(trials):
    s += is24()
s
# 3798

0语句失败时返回if,这对s总和没有贡献。