如何编写一个递归函数,返回由lst元素的正方形组成的列表?

时间:2014-04-15 00:47:55

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

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

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

最后一行显然是错误的

3 个答案:

答案 0 :(得分: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 []

答案 1 :(得分: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 :(得分:1)

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