在Python中创建简单的二进制搜索函数

在Python中创建简单的二进制搜索函数,python,binary-search,Python,Binary Search,基于LeetCode问题解决方案,我正在练习制作二进制搜索算法。我在下面写了这篇文章,混合使用了LeetCode解决方案中的代码和新代码。运行时,它无法按预期打印最终字符串 编辑:我忘了提到,除了不打印到控制台之外,代码在预期的时间内执行良好,没有错误 二进制搜索函数使用与LeetCode问题几乎相同的精确代码,并添加了计数器 我最好的猜测是While循环条件有问题,不过当我将它改为While True时,在if语句中使用'break'表示guess(mid)==0时,它根本不起作用 代码如下:

基于LeetCode问题解决方案,我正在练习制作二进制搜索算法。我在下面写了这篇文章,混合使用了LeetCode解决方案中的代码和新代码。运行时,它无法按预期打印最终字符串

编辑:我忘了提到,除了不打印到控制台之外,代码在预期的时间内执行良好,没有错误

二进制搜索函数使用与LeetCode问题几乎相同的精确代码,并添加了计数器

我最好的猜测是While循环条件有问题,不过当我将它改为While True时,在if语句中使用'break'表示guess(mid)==0时,它根本不起作用

代码如下:

target = int(input("Enter the target value.\n"))
maximum = int(input("Now, enter maximum value, for range of search.\n"))

def binary_search_func(n):
    """Search for a specific value within a range of 1 to n."""    

    low = 1
    high = n
    count = 1
    
    while low <= high:
        mid = int(low + (high - low) / 2)

        if guess(mid) == 0:
            print(f"Found {mid}, taking {count} turns.")
        
        elif guess(mid) == 1:
            low = mid + 1
            
        elif guess(mid) == -1:
            high = mid - 1
        
        count += 1


def guess(num):
    """Return value, depending upon whether guessed val == target val."""

    if num == target:
        return 0

    elif num > target:
        return 1

    elif num < target:
        return -1

binary_search_func(maximum)
target=int(输入(“输入目标值”。\n”))
最大值=int(输入(“现在,输入最大值,用于搜索范围。\n”))
def二进制搜索函数(n):
“”“搜索1到n范围内的特定值。”
低=1
高=n
计数=1
虽然目标较低:
返回1
elif num<目标:
返回-1
二进制搜索函数(最大值)
尝试以下代码:

# Returns index of x in arr if present, else -1 
def binary_search(arr, low, high, x): 
  
    # Check base case 
    if high >= low: 
  
        mid = (high + low) // 2
  
        # If element is present at the middle itself 
        if arr[mid] == x: 
            return mid 
  
        # If element is smaller than mid, then it can only 
        # be present in left subarray 
        elif arr[mid] > x: 
            return binary_search(arr, low, mid - 1, x) 
  
        # Else the element can only be present in right subarray 
        else: 
            return binary_search(arr, mid + 1, high, x) 
  
    else: 
        # Element is not present in the array 
        return -1
  
# Test array 
arr = [ 2, 3, 4, 10, 40 ] 
x = 10
  
# Function call 
result = binary_search(arr, 0, len(arr)-1, x) 
  
if result != -1: 
    print("Element is present at index", str(result)) 
else: 
    print("Element is not present in array")

您将进入二进制范围的错误一侧。当
guess
返回-1时,应该查看右侧,反之亦然

第二,当你有一个匹配,你应该退出循环,否则它将无限继续下去

if guess(mid) == 0:
    print(f"Found {mid}, taking {count} turns.")
    break  # add this
elif guess(mid) == -1:  # corrected
    low = mid + 1
elif guess(mid) == 1:   # corrected
    high = mid - 1

实际上,您不需要将
if
的最后一个块作为
elif
,因为这是剩下的唯一可能性。它可以是一个
else

OP已经知道工作版本(如他们在问题中所解释的)。他们正在寻找代码中的错误。所以“试试这个”没用好吧,我只是想帮忙