def search(num,seq=[]): if len(seq)==1: print(seq[0]) return seq[0] elif num<seq[len(seq)//2]: seq=seq[0:len(seq)//2] search(num,seq=seq[:]) elif num > seq[len(seq)//2]: seq=seq[len(seq)//2+1:] search(num,seq=seq[:]) else: return seq[len(seq)//2] seq=[1,2,3,4,5,6,7,8] seq.sort() print(seq) print(search(4,seq=seq[:]))
[1, 2, 3, 4, 5, 6, 7, 8] 4 None
望解决,这是一个二分法使用案例
每一个函数在末尾都隐藏了一句 return None
,除非你写了自己的return语句
def search(num):
global seq
if len(seq) == 1:
print(seq[0])
return seq[0]
elif num < seq[len(seq)//2]:
seq = seq[0:len(seq)//2]
print(seq)
return search(num)
elif num > seq[len(seq)//2]:
seq = seq[len(seq)//2+1:]
print(seq)
return search(num)
else:
return seq[len(seq)//2]
seq = [1, 2, 3, 4, 5, 6, 7, 8]
seq.sort()
print(seq[:])
print(search(4))
谢谢
楼上正解,递归时每一个判断分支都要return