user3490784
user3490784

Reputation: 21

How to write a recursive function that returns a list made up of squares of the elements of lst?

Im not sure how to get my recursion to work properly or keep from infinitely repeating. This is what i have so far:

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

last return line is obviously wrong

Upvotes: 1

Views: 5016

Answers (3)

KingKong BigBong
KingKong BigBong

Reputation: 313

def SquareArea(width):
if width == 0:
    return 0
else:
    return SquareArea(width-1) + (2*width-1)

This is a recursive function I've recently used to find the area of a square. And since the area of a square is Side*Side, one can use it to find the square of any function. Now all that is required of you is to make a loop, eg:

for i in range (list):

and implement this function on i Or maybe use while loop.

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

And then return the newList

Upvotes: 1

Nayuki
Nayuki

Reputation: 18533

You have it almost right, but the key is to mind your types. In your code:

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

We just need two small fixes:

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

Upvotes: 1

ooga
ooga

Reputation: 15501

Another possibility:

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

An even shorter version (as Cristian Ciupitu mentions below) is:

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

Upvotes: 2

Related Questions