【问题标题】:recursive sequential search does not return value递归顺序搜索不返回值
【发布时间】:2014-09-03 12:47:30
【问题描述】:

我正在 Python 上实现递归顺序搜索,如下所示:

def search(list1,n,pos):
    if n==list1[0]:
        return pos
    else:
        if list1==[]:
            return -1
        else:
            pos=pos+1
            list1.pop(0)
            return search(list1,n,pos)

def searchCall(n):
    anylist=[1,2,3,4,5,6,7,8,9,10]
    pos=0
    search(anylist,n,pos)

def main():
    i=searchCall(8)
    print i

if __name__=="__main__":
    main()

所以我要做的是尝试在列表中找到元素 n,并且在每次递归调用中,我都会弹出列表的第一个元素,并使用剩余的列表再次调用搜索。问题是当我把这个:

if n==list1[0]:
        print pos

它打印找到元素的位置,但是当我更改为:

return pos

它打印无

当没有找到该元素时,它应该返回 -1,而是显示以下错误消息:

if n==list1[0]:
IndexError: list index out of range

有什么帮助吗?

谢谢

【问题讨论】:

    标签: python recursion


    【解决方案1】:

    当一个元素没有找到时,你已经弹出了列表中的每一项,所以它的长度是0。这意味着你应该在开始时检查那个条件:

    def search(list1,n,pos):
        if list1==[]:
            return -1
    
        if n==list1[0]:
            return pos
        else:
            pos=pos+1
            list1.pop(0)
            return search(list1,n,pos)
    
    def searchCall(n):
        anylist=[1,2,3,4,5,6,7,8,9,10]
        pos=0
        print search(anylist,n,pos)
    

    编辑:正如Innox所说,只要你调用searchCall,你就很好,因为它每次都会实例化一个新列表,但search会消耗你的干草堆,所以它是一个时间搜索。

    【讨论】:

      【解决方案2】:

      你必须小心。

      首先,当值存在时,您的函数会按预期工作。刚刚做了 list1 = [1,2,3,4,5] 并调用了 search(list1,3,0) 并得到了 2 作为答案。

      您的实现的一个问题是它会弹出列表的值。因此,如果您尝试重用该列表,它将是不完整的。搜索调用后,list1 为 [3,4,5]。

      第二。当值不在列表中时,您的实现是错误的。基本上你应该在 n == list[0] 之前执行 list1 == [] 检查(或 len(list1) == 0)。

      【讨论】:

        【解决方案3】:

        这是因为你没有返回search(anylist,n,pos)的值 这就是为什么它只打印无。因为函数本身没有返回任何东西,因此当你想打印结果时,它是 None。 当您返回search 的结果时,您可以打印searchCall 函数的结果。

        您必须将函数更改为:

        def searchCall(n):
            anylist=[1,2,3,4,5,6,7,8,9,10]
            pos=0
            return search(anylist,n,pos)
        

        并且您得到了例外,因为您首先要求列表中的第一项在列表为空的情况下不存在。

        所以我建议对search函数进行这种修改

        def search(list1,n,pos):
            if list1==[]:
                return -1
            elif n==list1[0]:
                return pos;
            else:
                pos=pos+1
                list1.pop(0)
                b= search(list1,n,pos)
                return b;
        

        您首先验证列表是否为空,然后继续。

        编辑:

        只是为了让它完整...... 使用此 main 函数,它会打印 -1

        def main():
            print searchCall(15);
        

        这个main函数打印3

        def main():
            print searchCall(4);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-01-11
          • 1970-01-01
          • 2013-07-13
          • 2017-07-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多