擅长:python、mysql、java
<p>你的代码非常正确。您只是忘记了在递增<code>i</code>时重置<code>higher</code>和<code>lower</code>的值。你知道吗</p>
<p>下面是代码的工作版本(用于python2)</p>
<pre><code>def take_guess(lower, higher):
return lower + (higher - lower)/2
lower = 0
higher = 100
t = 1
l = []
for i in range(1,100):
###########################
# This is the only change!
lower = 0
higher = 100
###########################
while True:
# You can watch exactly what's happening by uncommenting the following line:
# print("i={}\t lower={}\t higher={}".format(i, lower, higher))
guess = take_guess(lower, higher)
if guess == i:
l.append(t)
t = 1
break
elif guess > i:
higher = guess
t += 1
continue
elif guess < i:
lower = guess
t += 1
continue
print sorted(l)[-1]
</code></pre>