递归猜测法

2024-09-28 20:48:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python3.4,我正在尝试做一个递归的猜测游戏。游戏应该有一个最小值和一个最大值,并且有一个“魔法”数字。游戏将生成一个介于x和y之间的随机数,然后要求用户插入y表示是,l表示太低,h表示过高。如果是“祝贺信息”,则退出。如果它太低,取最小值x,再加1,这就是新的最小值。同样的逻辑对于h过高。然后重新生成随机数。我被困在哪里调用递归。在

def recursive_guess(x,y,):
correct = False
while not correct:

    print('I will guess a number y for yes, l for too low, h for too high')
    guess = random.randrange(x, y)
    print(guess)
    anwser = input('y for yes l for low h for high')
    if anwser == 'y':
      print('Got it right')
      correct = True
    elif anwser == 'l':
      guess = random.randrange(minVal + 1, maxVal)
   elif anwser == 'h':
     guess = random.randomrange(minVal, maxVal-1)

Tags: 游戏forrandomyeslowtooprinthigh
2条回答

让我们切换到高级伪代码,并给变量起更好的名称,因为我认为您正被语法细节所困扰,而您的头脑中还没有您的算法的大局。在

def recursive_guess(lower_bound, upper_bound):
  guess = random guess in range [lower_bound, upper_bound]
  print guess
  request user response
  response = <get user response>
  if guess was too high:
    upper_bound = guess - 1
  elif guess was too low:
    lower_bound = guess + 1
  else:
    return guess
  # assuming we reached this point without returning,
  # we need to do a recursive call because guess was wrong
  return recursive_guess(lower_bound, upper_bound)

在给定的代码中,您似乎从递归方法开始,但当您再次将猜测更新为一个新的随机值时,您就(潜意识地)切换到迭代方法。如果您在函数的末尾执行与开始时相同的操作,这可能会提示您可能已经递归了。在

把递归看作是让你的任务稍微小一点,那么你就已经完成了。在这种情况下,如果我们可以减小窗口大小(upper_bound - lower_bound),那么我们就完成了我们的工作。递归将从那里开始处理它,只要我们有一个基本情况。在这个场景中,基本情况是正确的猜测,在这种情况下,我们立即返回。在

您应该更改minVal,然后使用它,而不是guess = random.randrange(minVal + 1, maxVal),如下所示:

minVal = guess + 1
guess = random.randrange(minVal, maxVal)

否则,minVal和maxVal将无法接近正确的数字;elif语句中的猜测每次都是相同的,因为minVal和maxVal实际上没有改变。另外,我看不到minVal和maxVal设置为x和y的位置

编辑:不确定递归性从何而来。如果您想让这个函数递归,您可以将它从while循环中取出并让它自己调用,即recursive_guess(guess + 1, y),而不是上面的行。在

相关问题 更多 >