【问题标题】:Finding numbers in a list using binary search need assistance使用二进制搜索在列表中查找数字需要帮助
【发布时间】:2013-09-27 05:19:28
【问题描述】:
nums = [734, 533, 449, 69, 869, 965, 656, 145, 913, 874, 987, 315, 967, 707]
nums.sort()
b=int(input("What number are you searching for?(Binary) "))
if b<nums[0] or b>nums[len(nums)-1]:
    print("The number you entered it out of list range")
    quit()
while True:
    if len(nums)==1 and nums[0]!=b:
        print("The number has not been found")
        break
    mid=nums[len(nums)//2]
    if mid==b:
        print("The number has been found")
        break
    elif mid>b:
        nums=nums[:len(nums)//2]
    else:
        nums=nums[len(nums)//2:]

这种二分搜索有效,但我的老师说他不想让我切片,我不知道那是什么意思。需要帮助弄清楚如何设置左右边界。

【问题讨论】:

  • nums[:len(nums)//2] 正在切片。您的老师可能希望您使用两个变量来保持上限和下限。
  • 我刚刚添加了排序功能

标签: python list find binary-search slice


【解决方案1】:

让我给你一点提示

mid = (start + end) // 2
if num[mid] > b:
  end = mid

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-03
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 2017-11-08
    • 1970-01-01
    • 2011-04-03
    相关资源
    最近更新 更多