- 2

# fun with maths recursion

The provided code uses recursion to calculate the sum of all items in the input list. Change the code to calculate and output the sum of the squares of all the list items def calc(list): if len(list)==0: return 0 else: return list[0] + calc(list[1:]) list = [1, 3, 4, 2, 5] x = calc(list) print(x)

6 odpowiedzi

+ 8

def calc(list):
if len(list)==0:
return 0
else:
return list[0]**2 + calc(list[1:])
list = [1, 3, 4, 2, 5]
x = calc(list)
print(x)

+ 5

So what's your question?
Please post only programming-related questions in sololearn. Q&A discussion is only for asking programming-related questions. You can post it in your activity feed and also you can post it in the comments of the python recursion lesson:
https://www.sololearn.com/Discuss/1316935/?ref=app
https://www.sololearn.com/post/52212/?ref=app
https://www.sololearn.com/post/903/?ref=app

+ 5

I fail to understand how this creates a recursion...
else:
return list[0]**2 + calc(list[1:])
I see how index 0 in the list gets raised to the power of 2, and then the second bit concatenated calls upon the same function which I presume is meant to keep adding what's been calculated thus far... but who is telling the function to keep iterating the items in list?
I don't understand the logic behind the else statement. Could someone dumb it down for me, please?

+ 3

To calculate and sum squares of the `list` items you multiply the LHS operand of the + operator by itself in the `else` block.
P.S. Avoid use of built-in class name for variable name. Use other name rather than 'list' for a `list` object.
def calc( lst ):
if len( lst ) == 0:
return 0
return ( lst[0] * lst[0] ) + calc( lst[1:] )
lst = [1, 3, 4, 2, 5]
x = calc( lst )
print( x )

0

set1 = {2, 4, 5, 6}
set2 = {4, 6, 7, 8, 11, 42, 2}
#your code goes here
print(set1 & set2)

0

list=[1,3,4,2,5]
list[0]=1
list[1:]=[3,4,2,5]
When you do: return list[0]**2+calc(list[1:]),
realize that the first element of the original list, list[0] has been squared, and a new temporary list, say temp_list, has been generated in the calc() function.
In this new list, the first element, temp_list[0]=list[1]=3, which is again getting squared and another temporary list is generated from ITS 2nd element to final element, and the recursion goes on.
Hence, return list[0]**2+calc(list[1:])