2013-05-09 248 views
0

我有一個家庭作業,用於模擬仿木棉花。我試圖找出如何擴大該計劃以解決關閉問題,並返回每個玩家的號碼。我在simNGames()中添加了一個循環來計算關閉。我想返回這些值並在摘要中打印出來。如何從Python 3中的函數打印這些返回值?

def simNGames(n, probA, probB): 
    winsA = 0 
    winsB = 0 
    shutoutA = 0 
    shutoutB = 0 
    for i in range(n): 
     scoreA, scoreB = simOneGame(probA, probB) 
     if scoreA > scoreB: 
      winsA = winsA + 1 
     else: 
      winsB = winsB + 1 
    for i in range(n): 
     scoreA, scoreB = simOneGame(probA, probB) 
     if scoreA == 15 and scoreB == 0: 
      shutoutA = shutoutA + 1 
     if scoreA == 0 and scoreB == 15: 
      shutoutB = shutoutB + 1 

     return winsA, winsB, shutoutA, shutoutB ## The program breaks when I add 
               ## shutoutA, and shutoutB as return val            

如果任何人都可以引導我在正確的方向它將不勝感激。我得到一個ValueError:太多的值解開(預期2),當我將關閉添加到返回值。這裏是整個程序:

from random import random 

def main(): 
    probA, probB, n = GetInputs() 
    winsA, winsB = simNGames(n, probA, probB) 
    PrintSummary(winsA, winsB) 


def GetInputs(): 
    a = eval(input("What is the probability player A wins the serve? ")) 
    b = eval(input("What is the probablity player B wins the serve? ")) 
    n = eval(input("How many games are they playing? ")) 
    return a, b, n 



def simNGames(n, probA, probB): 
    winsA = 0 
    winsB = 0 
    shutoutA = 0 
    shutoutB = 0 
    for i in range(n): 
     scoreA, scoreB = simOneGame(probA, probB) 
     if scoreA > scoreB: 
      winsA = winsA + 1 
     else: 
      winsB = winsB + 1 
    for i in range(n): 
     scoreA, scoreB = simOneGame(probA, probB) 
     if scoreA == 15 and scoreB == 0: 
      shutoutA = shutoutA + 1 
     if scoreA == 0 and scoreB == 15: 
      shutoutB = shutoutB + 1 

     return winsA, winsB 

def simOneGame(probA, probB): 
    serving = "A" 
    scoreA = 0 
    scoreB = 0 
    while not gameOver(scoreA, scoreB): 
     if serving == "A": 
      if random() < probA: 
       scoreA = scoreA + 1 
      else: 
       serving = "B" 

     else: 
      if random() < probB: 
       scoreB = scoreB + 1 
      else: 
       serving = "A" 
    return scoreA, scoreB 

def gameOver(a, b): 
    return a == 15 or b == 15 

def PrintSummary(winsA, winsB): 
    n = winsA + winsB 
    print("\nGames simulated:", n) 
    print("Wins for A: {0} ({1:0.1%})".format(winsA, winsA/n)) 
    print("Wins for B: {0} ({1:0.1%})".format(winsB, winsB/n)) 


if __name__ == '__main__': main() 

回答

2

當你調用該函數:

winsA, winsB = simNGames(n, probA, probB) 

你期待的只有兩個值(winsA,winsB),但返回四強。

+0

@ Lee Daniel Crocker。謝謝!使用多個功能可能會非常混亂。 – 2013-05-10 00:17:20