学习python,目前正在学习解决问题的二分法。我正在编写应使用户的猜测从0到100并尝试使用二等分找到该猜测的代码。这是代码:
answer = raw_input('Please think of a number between 0 and 100')
#I've been using 80 as my test case
low = 0
high = 100
guess = (low+high)/2
while guess != answer:
if guess < answer:
low = guess
else:
high = guess
guess = (low+high)/2
我已经意识到,当我的猜测<answer为假时,else块不会执行,因此我的高位永远不会改变。为什么会这样呢?我在这里俯瞰什么吗?
您需要将用户输入转换为整数(raw_input()
返回一个字符串):
answer = int(raw_input(...))
比较失败,因为您稍后将整数与字符串进行比较(在Python2中有效,但在Python3中无效):
>>> 10 < "50"
True
>>> 75 < "50"
True
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句