【问题标题】:Binary search of a number within a list in Python [duplicate]Python中列表中数字的二进制搜索[重复]
【发布时间】:2016-07-01 06:14:03
【问题描述】:

我正在研究一个列表中数字的二进制搜索,并遇到了this discussion

我在其他地方提到过分别使用偶数和奇数列表。但是这种语言是特定的吗?信息有点混乱。

对于二分搜索,我知道高级我需要执行以下步骤,

  • 按升序对列表进行排序
  • 检查列表中的中间项是否是我们完成的数字
  • 如果不是,如果数字大于中间数字,去掉下半部分
  • 如果搜索到的数字低于中间数字,则去掉上半部分
  • 不断重复直到找到数字

列表可以是升序或降序,可以是floatint 数字。 执行上述伪代码的pythonic方式是什么? 我在 windows 上使用 python 2.7.x。

** 编辑 ** 提到的讨论不包括偶数和奇数列表(至少我看不到任何
我想要求对此进行更多说明,例如,
- 如果我需要区别对待偶数列表
- 有没有办法在 python 中解决这个问题

【问题讨论】:

  • Pythonic 方式是the answer 链接问题。
  • 用户还询问了evenodd 列表。我的回答涵盖了这一点。
  • @anil_M :感谢您还涵盖了even , odd 列出问题的一部分。整数除法是否适用于整数和浮点列表。我会试试你的代码。
  • 我们正在划分元素的数量而不是它们的值(float / int)等。因此,您的列表是否有 10 个 int 数字或 10 个 float 数字 10 /3 will be still equal to 3。此外,您需要相应地替换 main 函数以生成浮动列表和浮动随机数。希望这会有所帮助。

标签: python algorithm


【解决方案1】:

除了 bisect 和(如讨论中所列)之外,您还可以创建自己的函数。 以下是一种可能的方式。

如果您在 python 中使用整数除法,它将处理偶数/奇数列表。例如10 / 3 = 39 / 3 = 3

示例代码

import random
def binarySearch(alist, item):
        first = 0
        last = len(alist) - 1
        found = False

        while first<=last and not found:
            midpoint = (first + last)//2            
            if alist[midpoint] == item:
                found = True
            else:
                if item < alist[midpoint]:
                    last = midpoint-1
                else:
                    first = midpoint+1  
        return found

def findThisNum(mynum):

    testlist = [x for x in range(listlength)]

    print "testlist = ", testlist
    print "finding number ", mynum

    if (binarySearch(testlist, findnum)) == True:
        print "found %d" %mynum
    else:
        print "Not found %d" %mynum




#### Main_Function ####

if __name__ == "__main__":
    #

    #Search 1 [ Even numbered list ]
    listlength = 10    
    findnum = random.randrange(0,listlength)
    findThisNum(findnum)     

    #Search 2 [ [ Odd numbered list ]
    listlength = 13    
    findnum = random.randrange(0,listlength)
    findThisNum(findnum)

    #search 3  [ find item not in the list ]

    listlength = 13    
    findnum = random.randrange(0,listlength) + listlength
    findThisNum(findnum)

输出

Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
testlist =  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
finding number  4
found 4
testlist =  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
finding number  9
found 9
testlist =  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
finding number  21
Not found 21

【讨论】:

  • 您好,该解决方案适用于偶数和奇数列表以及浮点列表。一步一步的概念更容易理解。出于测试目的尝试了手动浮动列表。 - 谢谢。
猜你喜欢
  • 1970-01-01
  • 2022-06-19
  • 2017-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-16
相关资源
最近更新 更多