2015-11-05 155 views
0

我在Python中使用随机模拟骰子游戏。然后我模拟游戏的次数,看看玩家多久击败经销商。我有一个带有种子的测试文件来检查我的代码,但是我的数字略有偏差。我认为错误在于结构,但似乎无法弄清楚究竟是什么。模拟骰子游戏1000次

骰子辊

def quietRoll(): 
    return random.randrange(1,7) + random.randrange(1,7) 

骰子模拟

def quietCraps(): 

    #first roll 

    firstRoll = quietRoll() 
    if firstRoll in (7,11): 
     return 1 
    elif firstRoll in (2,3,12): 
     return 0 

    #every other roll 

    newDice = quietRoll() 
    while newDice not in (7, firstRoll): 
     newDice = quietRoll() 
     if newDice == firstRoll: 
      return 1 
     if newDice == 7: 
      return 0 

运行掷骰子的n倍量

def testCraps(n): 
    count = 0 
    playerWin = 0 
    while count <= n: 
     if quietCraps() == 1: 
      playerWin += 1 
      count += 1 
     else: 
      count += 1 
return playerWin/n 

预计输出

Failed example: 

random.seed(5) 
testCraps(1000) 

Expected: 
    0.497 
Got: 
    0.414 
+0

而你的问题是...什么? –

+0

@DavidSchwartz什么导致期望的输出与实际不同? – 23k

+3

你是怎么想出你的预期产量的? – 2015-11-05 23:36:39

回答

2
newDice = quietRoll() 
while newDice not in (7, firstRoll): 
    newDice = quietRoll() 
    if newDice == firstRoll: 
     return 1 
    if newDice == 7: 
     return 0 

如果7firstRoll首次newDice的土地,你脱落的功能没有碰到一个return语句,函数默认返回None

由于return语句结束的功能(停止功能,可以执行任何循环和跳过任何函数的其余代码的),你可以通过具有循环是while True和循环之前未初始化newDice解决这个问题:

while True: 
    newDice = quietRoll() 
    if newDice == firstRoll: 
     return 1 
    if newDice == 7: 
     return 0 

或者,你可以移动if检查圈外的,所以他们发生一次的模具已经降落在7firstRoll,无论这种情况发生内或外循环:

newDice = quietRoll() 
while newDice not in (7, firstRoll): 
    newDice = quietRoll() 
if newDice == firstRoll: 
    return 1 
if newDice == 7: 
    return 0 
+0

什么是替代方式来写它,所以不会发生,我是一个初学者,所以我为这个愚蠢的问题道歉。 – 23k

+0

@ 23k:答案扩展。 – user2357112