python二分法猜数
时间: 2023-11-26 12:48:46 浏览: 98
python实现猜数游戏
以下是一个简单的Python二分法猜数的例子:
```python
import random
def binary_search(number, guess_list):
low = 0
high = len(guess_list) - 1
while low <= high:
mid = (low + high) // 2
guess = guess_list[mid]
if guess == number:
return mid
if guess > number:
high = mid - 1
else:
low = mid + 1
return None
if __name__ == '__main__':
guess_list = list(range(1, 101))
number = random.randint(1, 100)
print("请猜测一个1到100之间的数字:")
while True:
guess = int(input())
result = binary_search(guess, guess_list)
if result is None:
print("猜错了,请再试一次:")
elif result == number:
print("恭喜你,猜对了!")
break
elif result < number:
print("猜小了,请再试一次:")
else:
print("猜大了,请再试一次:")
```
阅读全文