import random
print("Welcome to the Number Guessing Game!\n")
print("We are going to pick a number and have the computer guess it.")
answer = int(input("Pick a number between 1 and 100:\n"))
guess = random.randint(1, 100)
guesses = 1
while guess != answer:
if guess > answer:
guess = random.randint(1, guess)
print(guess)
elif guess < answer:
guess = random.randint(guess, 100)
print(guess)
guesses += 1
print("\nWhoopy, I guessed correct.\n")
print("It took me %s guesses to guess %s." % (guesses, answer))
这是我到目前为止所拥有的。我不确定如何构建 if 和 elif 以确保没有猜测
答案 0 :(得分:1)
我怀疑你想要两个额外的变量来限制你guess
的界限。试试这个:
low = 1
high = 100
guess = random.randint(low, high)
guesses = 1
while guess != answer:
if guess > answer:
high = guess - 1
print(guess)
elif guess < answer:
low = guess + 1
print(guess)
guess = random.randint(low, high)
guesses += 1
print("\nWhoopy, I guessed correct.\n")
print("It took me %s guesses to guess %s." % (guesses, answer))
如果你没有随机猜测,你实际上会做得更好,而是总是选择low
和high
之间的中点。这是binary search algorithm。
答案 1 :(得分:0)
您希望添加min
和max
变量以跟踪当前范围。
min = 1; max = 100
guess = random.randint(min, max)
guesses = 1
while guess != answer:
if guess > answer:
min = guess+1
print(guess)
elif guess < answer:
max = guess-1
print(guess)
guess = random.randint(min, max)
guesses += 1
答案 2 :(得分:0)
我不知道如何形成if和elif以确保没有猜测
您应首先将名称绑定到1
,100
值。然后你可以有意义地分配给他们。
while guess != answer:
if guess > answer:
range_max = guess - 1
guess = random.randint(range_min, guess)
print(guess)
elif guess < answer:
range_min = guess + 1
guess = random.randint(guess, range_max)
print(guess)
guesses += 1
答案 3 :(得分:0)
您可以立即生成所有猜测,然后修剪大于或小于猜测的猜测列表:
import random
print("Welcome to the Number Guessing Game!\n")
print("We are going to pick a number and have the computer guess it.")
answer = int(input("Pick a number between 1 and 100:\n"))
guesses=random.sample(range(1, 101), 100)
count = 1
guess=guesses.pop()
while guess != answer:
if guess > answer:
guesses=[e for e in guesses if e<guess]
print(guess)
elif guess < answer:
guesses=[e for e in guesses if e>guess]
print(guess)
guess=guesses.pop()
count += 1
print("\nWhoopy, I guessed correct.\n")
print("It took me %s guesses to guess %s." % (count, answer))