首页 新闻 搜索 专区 学院

关于return语句的诡异事件

0
[已解决问题] 解决于 2018-02-02 16:25
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,请各位帮忙解决

环儿的主页 环儿 | 初学一级 | 园豆:186
提问于:2018-01-29 15:53
< >
分享
最佳答案
0

至少也应该是这样的:

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))

 

奖励园豆:5
akisann | 菜鸟二级 |园豆:341 | 2018-01-31 17:15

谢谢

环儿 | 园豆:186 (初学一级) | 2018-02-02 16:25
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册