我正在尝试编写一个python程序,程序会猜出用户编号。我喜欢白痴,我接受的部分是数学,我觉得这是其中一个我已经工作了几个小时的事情,其他人将能够带来一个新的视角和轻松解决。我想开始我几乎完全取出用户组件。这是我到目前为止所遇到的,它被卡在逻辑部分上,并最终只是说它太低或太高,无限:
MIN=0
MAX=100
firstguess = MAX - MIN
firstguess = firstguess/2
while 1==1:
number = int(raw_input("Enter your number 0-100:"))
print firstguess
oldguess = firstguess
if firstguess > number:
print "First guess is too high."
raw_input()
guess = int(25)
print guess
while guess != number:
if guess > number:
print "My guess was too high."
raw_input()
nextguess = oldguess - guess
nextguess = nextguess/2
nextguess = guess - nextguess
oldguess = guess
guess = nextguess
elif guess == number:
print "I win!"
exit
elif guess < number:
print "My guess was too low."
raw_input()
nextguess = oldguess - guess
nextguess = nextguess/2
nextguess = nextguess + guess
oldguess = guess
guess = nextguess
elif firstguess == number:
print "I win!"
elif firstguess < number:
print "My first guess was too low."
raw_input()
guess = 75
print guess
print guess
while guess != number:
if guess > number:
print "My guess was too high."
raw_input()
nextguess = oldguess - guess
nextguess = nextguess/2
nextguess = guess - nextguess
oldguess = guess
guess = nextguess
elif guess == number:
print "I win!"
exit
elif guess < number:
print "My guess was too low."
raw_input()
nextguess = oldguess - guess
nextguess = nextguess/2
nextguess = nextguess + guess
oldguess = guess
guess = nextguess
答案 0 :(得分:2)
好的,1)我不知道python和2)我不知道你的代码做了什么,不能打扰弄清楚它。为什么?因为我认为你过度复杂了。
我相信您可以通过简单的二进制搜索来解决这个问题。在伪代码中:
low = 0 // lowest possible value of user's number
high = 100 // highest possible value of user's number
while low < high
guess = (low + high) / 2 // guess the average of low and hight
if guess is too low // if guess is too low
then low = guess + 1 // then the lowest possible value is guess + 1
if guess it too high // if guess is too high
then hight = guess - 1 // then the highest possible value is guess - 1
if guess equals the value
we've found the answer
at this point (low + high) / 2 should be the answer
该算法将搜索空间减半并检查用户号码的哪一侧。示例在1-10
范围内运行,其中用户的编号为3
。 L
代表低,H
代表高,G
代表猜测:
L G H | guess is too high so we set high to guess-1
0 1 2 3 4 5 6 7 8 9 10 |
|
L G H | guess is too low so we set low to guess+1
0 1 2 3 4 5 6 7 8 9 10 |
|
L H | guess is in the same position as low and is correct so
0 1 2 3 4 5 6 7 8 9 10 | we've found the number
答案 1 :(得分:1)
我可能正在做你的作业,但你似乎对这个问题做了一个诚实的尝试:
bounds = [0, 100]
minimum, maximum = bounds
number = int(raw_input('Pick a number [{0}-{1}]: '.format(minimum, maximum)))
while guess != number:
guess = int((maximum + minimum) / 2)
raw_input('Guessing {0}'.format(guess))
if guess > number:
maximum = guess
elif guess < number:
maximum = bounds[1]
minimum = guess
print 'I win!'
逻辑很简单:
number
的号码。