该程序不起作用,我想进行二分搜索,但只是在开始时它给了我全局错误。它说“搜索”没有定义。请帮助我,我的整个讲座都坚持下去。
def bsearch (s, e, first, last):
print first, last
if (last - first) < 2: return s[first] == e or s[last] == e
mid = (last - first) + (last - first)/2
if s[mid] == e: return True
if s[mid] > e: return bsearch(s, e, first, mid - 1)
return bsearch(s, e, mid + 1, last)
def search1 (s, e):
print bsearch(s, e, 0, len(s) - 1)
print 'Search complete'
def testSearch():
s = range(0,1000000)
raw_input('basic, -1')
print search(s,-1)
raw_input('binary, -1')
print search1(s,-1)
raw_input('basic, end')
print search(s,1000000)
raw_input('binary, end')
print search1(s,1000000)
s = range(0,10000000)
raw_input('basic, partway')
print search(s,1000000)
raw_input('basic, larger end')
print search(0,10000000)
>>> testSearch()
basic, -1
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
testSearch()
File "C:\Users\bangash\Documents\python files\lec8.py", line 17, in testSearch
print search(s,-1)
NameError: global name 'search' is not defined
答案 0 :(得分:1)
您的测试用例似乎在比较search
和search1
所以我想search
应该是一个尚未定义的线性(即基本)搜索函数
例如:
def search(s, e):
for item in s:
if item == e:
break
print 'Search complete'
答案 1 :(得分:-1)
我没有看到您定义search
的位置,但您确实将search1
指定为函数,但是您的名字有误吗?
只需将所有search(s,-1)
行更改为search1(s,-1)