1

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
user3490784
  • 21
  • 1
  • 4

3 Answers3

2

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 []
ooga
  • 15,423
  • 2
  • 20
  • 21
1

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
Nayuki
  • 17,911
  • 6
  • 53
  • 80
1
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