类列表数组python的递归线性搜索

时间:2017-03-01 02:20:09

标签: python list class recursion

您好我如何使用递归进行线性搜索而不是迭代地进行?这就是我目前正在努力做到的。我收到此错误

  

如果l [0] == key:

     

TypeError:'type'对象不可订阅TypeError:'type'对象   不可订阅l

@classmethod
def _linear_search_r(l,key, i=0):

    if l:  #Check if list is not empty
        if l[0] == key:
            return i 

        s = _linear_search_r(l[1:],key, (i + 1))
        if s is not False:
            i = s
            return i

    return False

2 个答案:

答案 0 :(得分:2)

这是一个类方法,因此它接收的第一个参数(你命名为l)是对类本身的引用。

如果l应该是所述类的实例,请删除@classmethod装饰器。如果l应该与该类无关,则将@classmethod更改为@staticmethod(后者不会隐式接收该类型作为第一个参数)或添加clsl前面的争论。

如果目标是处理实例属性,那么我建议使用递归辅助方法(即类或静态)使顶级函数成为实例方法。例如:

# Public instance method that delegates to recursive class method
def linear_search(self, key):
    return self._linear_search_r(self._values, key)

@classmethod
def _linear_search_r(cls, l, key, i=0):

    if l:  #Check if list is not empty
        if l[0] == key:
            return i 

        s = cls._linear_search_r(l[1:],key, (i + 1))
        if s is not False:
            i = s
            return i

    return False

答案 1 :(得分:1)

只有三种情况需要担心:

  • 如果输入列表为空,则引发异常
  • 如果"首先"列表的元素是匹配的,返回索引。
  • 如果"首先"列表的元素不匹配,进行递归调用并返回其值。

我把"第一"在引号中,因为虽然将输入列表的尾部传递给每个递归调用是优雅的,但构造尾部的开销使得这样做效率低下。相反,我们只是传递递增的i以用作索引来遍历列表。

# Elegant, but inefficient
def _linear_search(l, key):
    if not l:
        raise LookupError(key)
    elif l[0] == key:
        return 0
    else:
        return 1 + _linear_search(l[1:], key)

# Clumsy, but faster
# Note: generally, you do not explicitly call this
# with an explicit value for i; it should only be
# used as a 
def _linear_search(l, key, i=0):
    if not l:
        raise LookupError(key)
    elif l[i] == key:
        return i
    else:
        return _linear_search(l, key, i+1)

# Slightly more complicated, but hides the i argument from the user
def _ls_helper(l, key, i):
        if not l:
            raise LookupError(key)
        elif l[i] == key:
            return i
        else:
            return _ls_helper(l, key, i+1)

def _linear_search(l, key):
    return _ls_helper(l, key, 0)