我正在努力使用一些简单的算法,这应该让python在尽可能少的猜测中猜测给定的数字。它似乎在运行,但速度非常慢。我究竟做错了什么。我已经阅读了有关此问题的几个主题,但无法找到解决方案。我是初学程序员,所以欢迎任何提示。
min = 1
max = 50
number = int(input(("please choose a number between 1 and 50: ")))
total = 0
guessed = 0
while guessed != 1:
guess = int((min+max)/2)
total += 1
if guess == number:
print("The number has been found in ",total," guesses!")
guessed = 1
elif guess > number:
min = guess + 1
elif guess < number:
max = guess - 1
由于
PS。我知道程序没有检查输入错误;)
答案 0 :(得分:4)
你的逻辑是倒退的。当你猜得太高时,你希望降低 max
,当你猜得太低时,提升 min
。试试这个:
if guess == number:
print("The number has been found in ",total," guesses!")
guessed = 1
elif guess > number:
max = guess - 1
elif guess < number:
min = guess + 1
答案 1 :(得分:1)
除了逻辑向后,你不应该使用min和max作为变量名。它们是python函数。您也可以使用True,并在猜到数字时立即中断。
while True:
guess = (mn + mx) // 2
total += 1
if guess == number:
print("The number has been found in {} guesses!".format(total))
break
elif guess < number:
mn = guess
elif guess > number:
mx = guess
您还会看到,不会在猜测中添加或减去1,而是会在较少的步骤中找到该数字。
答案 2 :(得分:0)
from random import randint
print('choose a number in your brain and if guess is true enter y else any key choose time of guess: ')
print("define the range (A,B) :")
A = int(input("A: "))
B = int(input("B: "))
time = int(input("time:"))
while time != 0:
ran = randint(A, B)
inp = input(f"is this {ran} ?")
time -= 1
if inp == "y":
print("bla bla bla python wins!")
break
print("NOPE!")
if time == 0:
print("computer game over!")
break