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)
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
+ 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.
+ 1
Thanks bro but I want to know how the recursion works here.
+ 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.
0
Is equal to sum+=x^2 for x in list
0
Ok
0
Thanks for the explanation
- 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
- 1
Results 55