3

我正在编写棒球比赛模拟。我希望能够运行多场比赛,看看不同的击球率如何影响结果。每场比赛都由“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()
4

3 回答 3

10

问题在于您对全局变量的使用。

在你的 game() 第一次运行后, outs 为 27。当你再次调用 game 时,它​​仍然具有相同的值,所以你的 while 循环立即退出。

于 2013-04-27T17:54:48.903 回答
0
import random

# determine whether player (with .300 batting average) gets a hit or an out
def game():
    global hits
    global outs
    hits = 0
    outs = 0
    while outs < 27:
        hits, outs = at_bat()
    else:
        print("game over!")
        print(hits)

def at_bat():
    global hits
    global outs
    number = random.randint(0,1000)
    if number < 300:
        hits += 1
    else:
        outs += 1
    return hits, outs

  # run 5 games
for i in range(0,5):
    game()

我总是发现 global 有时会搞砸,但是这段代码可以工作并为您提供不同的数字。outs每次你的游戏代码运行时总是 27,将它们重置为 0 确保你的游戏循环每次都会运行

于 2013-04-27T18:04:14.733 回答
0

啊,全局变量让人头疼……

实际上,如果您为每个循环重置这两个全局变量,您的代码会运行良好。所以:

for i in range(0,5):
    game()
    hits = 0
    outs = 0
于 2013-04-27T19:12:24.217 回答