【问题标题】:How to write a recursive function that returns a list made up of squares of the elements of lst?如何编写一个递归函数,返回一个由 lst 元素的平方组成的列表?
【发布时间】:2014-05-29 03:54:38
【问题描述】:

我不确定如何让我的递归正常工作或避免无限重复。 这是我到目前为止所拥有的:

def listSquareR(lst):
    if len(lst)== 1:
        return lst[0]**2
    else:
        return lst[0]**2+[listSquareR(lst[1:])]

最后一个返回行显然是错误的

【问题讨论】:

    标签: python list recursion computer-science perfect-square


    【解决方案1】:

    你几乎说对了,但关键是要记住你的类型。在您的代码中:

    def listSquareR(lst):
        if len(lst)== 1:
            return lst[0]**2  # Returning a number
        else:
            return lst[0]**2+[listSquareR(lst[1:])]  # Returning a number plus a list of a list
    

    我们只需要两个小修复:

    def listSquareR(lst):
        if len(lst)== 1:
            return [lst[0]**2]  # Returning a list
        else:
            return [lst[0]**2] + listSquareR(lst[1:])  # Returning a list plus a list
    

    【讨论】:

      【解决方案2】:

      另一种可能性:

      def listSquare(L):
        if L: return [L[0]**2] + listSquare(L[1:])
        else: return []
      

      一个更短的版本(正如 Cristian Ciupitu 在下面提到的)是:

      def listSquare(L):
        return [L[0]**2] + listSquare(L[1:]) if L else []
      

      【讨论】:

      • 甚至更短:return [L[0]**2] + listSquare(L[1:]) else [].
      • @CristianCiupitu:抱歉,这在语法上无效
      • @CristianCiupitu 您忘记了if L 之前的else 部分。否则,好一个!
      • 欲速则不达 :-)
      【解决方案3】:
      def SquareArea(width):
      if width == 0:
          return 0
      else:
          return SquareArea(width-1) + (2*width-1)
      

      这是我最近用来求正方形面积的递归函数。 而且由于正方形的面积是 Side*Side,因此可以使用它来找到任何函数的平方。 现在你需要做的就是做一个循环,例如:

      for i in range (list):
      

      并在 i 上实现此功能 或者也许使用 while 循环。

      newList=[]
      length = len(list)
      while i != length:
         newList.append(SquareArea(i))
      

      然后返回newList

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-02-03
        • 2019-04-08
        • 2010-10-09
        • 2016-01-24
        • 1970-01-01
        • 1970-01-01
        • 2020-07-24
        相关资源
        最近更新 更多