0

Please tell me how this code works:-

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)

25th Jun 2022, 6:03 AM
Vaibhav Pandey
9 Answers
+ 3
calc([1,3,4,2,5]) 1**2 + calc([3,4,2,5]) 1**2 + 3**2 + calc([4,2,5]) 1**2 + 3**2 + 4**2 + calc([2,5]) 1**2 + 3**2 + 4**2 + 2**2 + calc([5]) 1**2 + 3**2 + 4**2 + 2**2 + 5**2 + 0 1 + 9 + 16 + 4 + 25 + 0 55
27th Jun 2022, 2:00 AM
Bob_Li
Bob_Li - avatar
+ 6
Please take paper and pencil and analyse it yourself step by step. Although the concept of recursion is easy, must be experienced by going into detail a few times. See.... one can explain cricket 1000 hours. It won't enable you to become a good player.
25th Jun 2022, 12:22 PM
Oma Falk
Oma Falk - avatar
+ 1
Thanks bro but I want to know how the recursion works here.
25th Jun 2022, 6:25 AM
Vaibhav Pandey
+ 1
Side note: don't use reserved words, like "list", to name variables, functions, or anything else. It can get you side effects which are hard to debug.
25th Jun 2022, 6:44 PM
Emerson Prado
Emerson Prado - avatar
0
Is equal to sum+=x^2 for x in list
25th Jun 2022, 6:20 AM
Cristian Baeza Jimenez
Cristian Baeza Jimenez - avatar
0
Ok
26th Jun 2022, 3:42 AM
Vaibhav Pandey
0
Thanks for the explanation
27th Jun 2022, 2:24 AM
Vaibhav Pandey
- 1
list= [1,3,4,2,5] def calc(list): if len(list)==0: return 0 else: return list[0]**2+calc(list[1:]) x=calc(list) print(x
26th Jun 2022, 8:35 AM
Purushothman Green
Purushothman Green - avatar
- 1
Results 55
26th Jun 2022, 8:36 AM
Purushothman Green
Purushothman Green - avatar