此代码需要询问用户一个数字(即:32)。然后它应该告诉用户从 1 到 31 中选择一个数字。然后使用二分搜索来“猜测”一个数字(16 而不是 15),然后用户将键入该数字是否正确、过高或过低。我还认为在代码中添加某种函数会使其更合理,但我不知道如何实现它。
我让用户输入一个数字,然后开始猜测如果原始数字是 32,他们从 16 开始在想什么。但是,如果我说 H 表示 16 太高,它会输出 24,这是一个比16.
import numpy as np
low = 0
n = int(input("Enter n: "))
if n <= 0:
n = int(input("Please enter a positive number: "))
else:
array = np.arange(0, n, 1) # Fix the range to include 0 and n-1
print(f'Guess a number between 0 and {n - 1}')
while low <= n - 1: # Correct the condition to use n - 1
guess = low + (n - low) // 2 # Fix the calculation for the guess
answer = input(f'Is your number: {guess}? Please enter C for correct, H for too high, or L for too low.')
if answer == 'C':
break
elif answer == 'H':
n = guess # Adjust the range for a lower guess
else:
low = guess + 1 # Adjust the range for a higher guess
import numpy as np
def binary_search(low, high):
while low <= high:
guess = low + (high - low) // 2
answer = input(f'Is your number: {guess}? Please enter C for correct, H for too high, or L for too low.')
if answer == 'C':
print(f'Your number is {guess}.')
return
elif answer == 'H':
high = guess - 1
else:
low = guess + 1
print("Hmm, it seems like there was an error with the inputs.")
n = int(input("Enter a number: "))
if n <= 0:
n = int(input("Please enter a positive number: "))
print(f'Guess a number between 0 and {n - 1}')
binary_search(0, n - 1)
做了一些改变,现在认为它运行良好。还添加了猜数字时消息的一点奖励。