You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

二分查找实现代码报错:print语句引发语法错误问题排查

问题分析与修复方案

1. 直接触发语法错误的原因

你第19行的print binary_search(my_list, 3)是Python 2的语法,Python 3中print是内置函数,必须使用括号调用,正确写法为:

print(binary_search(my_list, 3))

2. 其他潜在问题(修复语法后仍需注意)

  • 整数索引异常:mid = (low + high)/2在Python 3中会返回浮点数(比如(0+4)/2=2.0),而列表索引必须是整数,直接用list[mid]会触发TypeError,需要改用整数除法运算符//:
    mid = (low + high) // 2
    
  • 内置类型名冲突:你用了list作为函数参数名,这会覆盖Python内置的list类型,可能导致后续代码出现意外问题,建议改成更合适的名称,比如nums:
    def binary_search(nums, item):
        low = 0
        high = len(nums)-1
        # 后续代码中把所有list替换为nums
    

修复后的完整代码

def binary_search(nums, item):
    low = 0
    high = len(nums)-1
    
    while low <= high:
        mid = (low + high) // 2
        guess = nums[mid]
        
        if guess == item:
            return mid
        if guess > item:
            high = mid - 1
        else:
            low = mid +1
    return None

my_list = [1,3,5,7,9]

print(binary_search(my_list, 3))  # 输出:1

内容的提问来源于stack exchange,提问作者underd0g

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 16:37:11