我正在编写棒球比赛模拟。我希望能够运行多场比赛,看看不同的击球率如何影响结果。每场比赛都由“at-bats”组成,其结果来自一个随机数。
问题是当我跑多场比赛时,每场比赛我都得到相同的结果。
我想 Python 正在记住函数的结果,并且只是使用它。我是 Python/CS 的新手,因此一直在尝试查找内存等问题,但没有找到我需要的答案。我感谢任何对资源的帮助或指导,我将不胜感激。谢谢
以下是一个简化版本,以帮助我解释问题。它只使用安打和出局,以 27 出局结束比赛。最后它循环了五场比赛。
import random
hits = 0
outs = 0
# determine whether player (with .300 batting average) gets a hit or an out
def at_bat():
global hits
global outs
number = random.randint(0,1000)
if number < 300:
hits +=1
else:
outs += 1
# run at_bat until there are 27 outs
def game():
global hits
global outs
while outs < 27:
at_bat()
else:
print "game over!"
print hits
# run 5 games
for i in range(0,5):
game()