fun with maths recursion | Sololearn: Learn to code for FREE!

-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)

7/4/2021 9:43:45 AM

Lokendra Gupta

3 Answers

New Answer

+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

+2

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

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)