def search(num,seq=[]): if len(seq)==1: # print("3") # assert seq[0]==num # num1=seq[0] return seq[0] elif num<seq[len(seq)//2]: # print("2") seq=seq[0:len(seq)//2] search(num,seq=seq[:]) return 2 elif num > seq[len(seq)//2]: # print("1") seq=seq[len(seq)//2+1:] search(num,seq=seq[:]) else: # print("5") return seq[len(seq)//2] def test(seq): return 2 seq=[1,2,3,4,5,6,7,8] seq.sort() print(search(6,seq=seq[:])) print(seq) print(test(seq))
None [1, 2, 3, 4, 5, 6, 7, 8] 2
上例为实现二分法的示例,输出search(6,seq)函数应该返回搜索值,但是总是返回None,请各位帮忙解决
至少也应该是这样的:
def search(num,seq=[]): if len(seq)==1: return seq[0] elif num<seq[len(seq)//2]: seq=seq[0:len(seq)//2] return search(num,seq=seq[:]) elif num > seq[len(seq)//2]: seq=seq[len(seq)//2+1:] return search(num,seq=seq[:]) else: return seq[len(seq)//2] def test(seq): return 2 seq=[1,1,2,3,4,5,6,7,8] seq.sort() print(search(6,seq=seq[:])) print(seq) print(test(seq))
但你的代码是返回搜索值(而非index),在不破坏源程序结构的情况下可以改成这样来返回index:
def search(num,seq=[]): mid=len(seq)//2 if len(seq)==1: return 0 elif num<seq[mid]: return mid+search(num,seq=seq[0:mid]) elif num > seq[mid]: return mid+search(num,seq=seq[mid+1:]) else: return mid def test(seq): return 2 seq=[1,1,2,3,4,5,6,7,8] seq.sort() print(search(6,seq=seq[:])) print(seq) print(test(seq))
谢谢