python递归函数返回值
以下是用递归实现有序数组的二分查找Python代码
def binarysearch(seq, x, lower = 0, upper = None):
if upper == None: upper = len(seq) - 1
middle = (lower + upper) / 2
if x == seq[middle]:
return middle
elif x > seq[middle]:
lower = middle + 1
else:
upper = middle - 1
if upper < lower:
print x, 'is not in', seq
return
return binarysearch(seq, x, lower, upper) #此处必须加上return,否则函数总是返回None
if __name__ == '__main__':
seq = [34, 67, 8, 123, 4, 100, 95]
seq.sort()
y = binarysearch(seq, 34)
print y