【问题标题】:recursion with a list in python在python中使用列表递归
【发布时间】:2020-02-06 11:18:56
【问题描述】:

我刚开始学习 python,有一些我似乎无法弄清楚的递归问题。最讨厌的是这个: 我需要构建一个函数ind(e,L),其中e 是一个int,L 是一个列表。

输入e 如果它在列表中,输出需要是它的索引 例如:

ind(42,[0,14,52,42,15]) -> 3

这是我到目前为止编写的代码,但我得到的索引始终为 0。有人可以向我解释我做错了什么吗?

def location(e,L):
    if L == []:
        return False
    elif e == L[0]:
        A = L[:-1].index(e)
        return A
    else:
        return location(e,L[1:])

print(location(14,[1,2,14,1]))

谢谢:)

【问题讨论】:

  • 首先,如果练习的目的是学习递归和自己实现定位功能,那为什么要使用.索引(这正是你想要的位置做的)里面?如果目标不是自己实现,为什么不直接使用索引?
  • 如果元素存在则完成递归的唯一情况是e == L[0]。那么你怎么能期望返回 0 以外的东西呢?

标签: python python-3.x list recursion


【解决方案1】:

更短的递归解决方案:

def ind(a, b):
   def _ind(a, b):
     return False if not b else (b[0] == a or 1+_ind(a, b[1:]))
   return _ind(a, b) - 1

print(ind(42,[0,14,52,42,15]))

输出:

3

如果你不介意抵消一:

def ind(a, b):
  return False if not b else (b[0] == a or 1+ind(a, b[1:]))

>>>ind(42,[0,14,52,42,15]) - 1

或者,使用默认参数:

def ind(a, b, c = 0):
   return False if not b else (c if b[0] == a else ind(a, b[1:], c+1))

>>>ind(42,[0,14,52,42,15])

【讨论】:

    【解决方案2】:

    只有当 e 位于索引 0 处时才返回(您可以跳过 L[:-1]... 术语,它始终为 0)并传播它不变。与其返回无意义的索引,不如返回递归数。最简单的方法是在函数递归时加 1。

    def location(element, sequence):
        if not sequence:
            # e is not in the list at all
            # it is not meaningful to return an index
            raise IndexError
        elif element == sequence[0]:
            # we already know where e is
            # since we checked it explicitly
            return 0
        else:
            # keep searching in the remainder,
            # but increment recursion level by 1
            return 1 + location(element, sequence[1:])
    

    【讨论】:

      【解决方案3】:

      我的解决方案有点不同。我从L 的右端开始寻找e。如果找到,那么索引就是L 的长度减去 1(因为 Python 索引以 0 开头)。

      这个实现不需要你做任何变量来存储索引,我认为这很整洁。

      def location(e, L):
          if L:
              if L[-1] == e:
                  return len(L)-1
              else:
                  return location(e, L[:-1])
          return False
      

      测试:

      >>> L = [0,14,52,42,15]
      >>> location(42, L)
      3
      

      【讨论】:

        【解决方案4】:

        需要注意的一点是,您的代码中的the time complexitythe space complexityO(n^2)。因为L[1:] 每次都会创建一个new list!在timespace 方面是O(n) 操作。


        一种正确的 Pythonic 方式是:

        def location(e, L):
            n = len(L)
        
            def _location(start):
                if start == n:
                    raise IndexError
        
                if L[start] == e:
                    return start
        
                return _location(start + 1)
        
            return _location(0)
        
        print(location(14, [1, 2, 14, 1]))
        

        输出:

        2
        

        时间复杂度:O(n)

        空间复杂度:O(n)(由于递归。)

        【讨论】:

          【解决方案5】:

          我也很新,但我认为这应该可以解决问题......

          
          def function(e,L):
              try:
                  x = 0
                  for val in L:
                      if e == val:
                          return(x)
                      else: x = x+1
              except:
                  print('List provided does not contain any values')
          

          x 将通过值计数并在索引等于列表中的值时返回。它还会返回多个匹配项,这可能会有所帮助。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2022-08-12
            • 1970-01-01
            • 1970-01-01
            • 2021-12-13
            • 2014-05-05
            • 2012-12-28
            • 2010-09-17
            相关资源
            最近更新 更多