代码之家  ›  专栏  ›  技术社区  ›  sstatic

我如何调整我的代码以使用二进制搜索来猜测我脑子里想的数字

  •  -1
  • sstatic  · 技术社区  · 2 年前

    此代码需要向用户询问一个数字(即:32)。然后它应该告诉用户从1到31中选择一个数字。然后使用二进制搜索来“猜测”一个数字(16而不是15),然后用户会键入该数字是否正确、过高或过低。此外,我认为在代码中包含某种函数会使它更明智,但我不知道如何实现它。

    我让用户输入一个数字,然后从16开始猜测他们的想法,如果原始数字是32。然而,如果我说16的H太高,它将输出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
    
    2 回复  |  直到 2 年前
        1
  •  0
  •   Arunbh Yashaswi    2 年前
    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 n: "))
    
    
    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)
    

    做了一些更改,现在认为运行良好。还增加了一点奖金的消息时,数字是猜测。最重要的是,通过将二进制搜索从中分离出来简化了它。

        2
  •  0
  •   felipepc1221    2 年前

    您可以将变量(任何高于low的值)声明为“high”,并替换while的“n-1”(while low<=high:),然后在用户输入“H”(high=guess-1)时更新变量“high)。我建议在更新“猜测”的逻辑中插入这个新变量

    推荐文章