我正在研究列表中某个数字的二进制搜索,并遇到了this discussion
在其他地方我提到了分别为偶数和奇数编号列表。但这种语言是否具体?这些信息有点混乱。
对于二进制搜索,我知道高级别我需要执行以下步骤,
列表可以是升序或降序,可以是float
个int
个数字。
什么是进行上述伪代码的pythonic方法?
我在Windows上使用python 2.7.x.
**编辑**
上面提到的讨论不包括偶数和奇数列表(至少我看不到任何
我想要求更多澄清,例如,
- 如果我需要区别对待奇数列表的话
- python中是否有一种方法可以处理
答案 0 :(得分:1)
除了bisect和(如讨论中所列),您可以创建自己的功能。 以下是一种可行的方法。
如果你在python中使用整数除法,它将处理偶数/奇数列表。作为例如10 / 3 = 3
和9 / 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