关于return语句的诡异事件


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 2seq=[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,请各位帮忙解决


天涯尽头无女友
浏览 635回答 1
1回答

梦里花落0921

至少也应该是这样的:def&nbsp;search(num,seq=[]):&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;len(seq)==1:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;seq[0]&nbsp;&nbsp;&nbsp;&nbsp;elif&nbsp;num<seq[len(seq)//2]: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;seq=seq[0:len(seq)//2]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;search(num,seq=seq[:])&nbsp;&nbsp;&nbsp;&nbsp;elif&nbsp;num&nbsp;>&nbsp;seq[len(seq)//2]: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;seq=seq[len(seq)//2+1:]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;search(num,seq=seq[:])&nbsp;&nbsp;&nbsp;&nbsp;else:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;seq[len(seq)//2]def&nbsp;test(seq):&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;2seq=[1,1,2,3,4,5,6,7,8] seq.sort()print(search(6,seq=seq[:]))print(seq)print(test(seq))&nbsp;但你的代码是返回搜索值(而非index),在不破坏源程序结构的情况下可以改成这样来返回index:&nbsp;def&nbsp;search(num,seq=[]): &nbsp;&nbsp;&nbsp;&nbsp;mid=len(seq)//2&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;len(seq)==1:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;elif&nbsp;num<seq[mid]:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;mid+search(num,seq=seq[0:mid])&nbsp;&nbsp;&nbsp;&nbsp;elif&nbsp;num&nbsp;>&nbsp;seq[mid]:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;mid+search(num,seq=seq[mid+1:])&nbsp;&nbsp;&nbsp;&nbsp;else:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;middef&nbsp;test(seq):&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;2seq=[1,1,2,3,4,5,6,7,8] seq.sort()print(search(6,seq=seq[:]))print(seq)print(test(seq))
打开App,查看更多内容
随时随地看视频慕课网APP