【问题标题】:Creating a number guessing game where the computer guesses the number, list slicing创建一个计算机猜数字的猜数字游戏,列表切片
【发布时间】:2020-06-24 19:33:25
【问题描述】:

我正在尝试创建一个程序,其中计算机从有序列表中猜测一个数字,如果它太高,那么列表被分割为只包含较低的数字,如果太低,列表被分割为只包括更高的数字。然后计算机再次猜测。

由于某种原因,列表没有正确切分。我没有真正看到模式,但这里有一个例子:

(我在想 46)

猜测:4
太低了
新列表:[5:99]
猜测:92
太高了
新列表:[5:96](应该是 [5:91])
猜测:63
太高了
新列表:[5:67](应为 [5:63])
猜测:58
太高了
新列表:[5:62](应该是 [5:58])
...

这是我的代码:

import random

guess_list = [x for x in range(1, 100)]
guess = random.choice(guess_list)

def computer_guessing_game(guess, guess_list):
  print(guess)
  response = input("is this correct, too high, or too low?: ")

  if response == "correct":
    print('smart computer')
  
  elif response == "too low":
    print("too low, try again")
    guess_list = [x for x in guess_list[guess:]]
    guess = random.choice(guess_list)
    print(guess_list)
    computer_guessing_game(guess, guess_list)
  
  elif response == "too high":
    print("too high, try again")
    guess_list = [x for x in guess_list[:guess]]
    guess = random.choice(guess_list)
    print(guess_list)
    computer_guessing_game(guess, guess_list)
  
computer_guessing_game(guess, guess_list)

【问题讨论】:

  • 你说得对,我不应该说二分搜索....计算机正在随机猜测列表中的数字
  • 您将索引与该索引处的值混淆了。
  • 模式为 4+92=96。 63+4=67。 58+4=62。这是因为在您对列表进行切片后,您的数组从不同的点开始
  • 存储最小值和最大值比存储整个数字列表更有效
  • [:guess] 与 guess=5 会给你直到 index 5(不包括),直到 value 5。如果你的数组是[4,5,6,7,8,9,10],结果将是[4,5,6,7,8],而不是[4,5]

标签: python recursion


【解决方案1】:

根据建议,我去掉了列表,而是使用了最小和最大数字:

guessing = random.randint(1, 100)
minimum = 1
maximum = 100
count = 1
def guessing_game_two(guessing, minimum, maximum, count):
  print(guessing)
  response = input("is this correct, too high, or too low?: ")

  if response == "correct":
    print('smart computer, and it only took you {} tries'.format(count))

  elif response == "too low":
    count += 1
    minimum = guessing + 1
    guessing = random.randint(minimum, maximum)
    guessing_game_two(guessing, minimum, maximum, count)

  elif response == "too high":
    count += 1
    maximum = guessing - 1
    guessing = random.randint(minimum, maximum)
    guessing_game_two(guessing, minimum, maximum, count)

guessing_game_two(guessing, minimum, maximum, count)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-20
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多