二分法查找猜数字python
时间: 2023-07-25 17:25:14 浏览: 124
python 实现 二分查找
好的,以下是一个简单的二分法查找猜数字的 Python 代码:
```python
import random
def binary_search(guess, low, high):
if low > high:
return -1
mid = (low + high) // 2
if guess == mid:
return mid
elif guess < mid:
return binary_search(guess, low, mid - 1)
else:
return binary_search(guess, mid + 1, high)
def guess_number():
low = 1
high = 100
target = random.randint(low, high)
print("I'm thinking of a number between 1 and 100. Can you guess what it is?")
while True:
guess = int(input())
if guess < low or guess > high:
print("Please enter a number between 1 and 100.")
else:
result = binary_search(guess, low, high)
if result == -1:
print("Sorry, you didn't guess my number. Try again!")
else:
print("Congratulations! You guessed my number in", result, "guesses.")
break
guess_number()
```
这个程序会随机生成一个 1 到 100 的数字,然后提示玩家猜测这个数字是多少。每次玩家猜测一个数字后,程序会告诉玩家猜的数字是高了还是低了,直到玩家猜中这个数字为止。程序使用了二分法来查找猜测的数字,所以可以快速地猜出正确的答案。
阅读全文