+ 1
Can anyone explain the recursion?
https://code.sololearn.com/c9FDedhV6EnI/?ref=app 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) When the code sees th5 line and reads the" calc(list[1:])" The code will see list0 = 1 Then reads the function(calc(list[1:])) again and now is 3 = list0
5 Answers
+ 2
Take a look at the result of this code đ
def calc(list):
if len(list)==0:
print('Recursion completed')
return 0
else:
a = list[0]
b = a**2
rec = calc(list[1:])
print(rec,'+',str(a)+'ÂČ =',b+rec)
return b+rec
print(calc([1, 3, 4, 2, 5]))
+ 1
list[0]**2 + calc(list[1:])
Calculating list[0] power 2 + (again calling function remaining list with [3, 4,2,5] so now list[0] for new function is 3
Finally returning like
1**2 + ( 3**2 + ( 4**2 + (2**2 + (5**2 +( 0 ) ))))
= 1 + (9 + ( 16 + ( 4 + ( 25 + 0) ) ) ) = 55
Hope it helps..
+ 1
Jayakrishnađźđł thanks bro it helped alot but why this zero
1**2 + ( 3**2 + ( 4**2 + (2**2 + (5**2 +(||||||| 0 )|||| ))))
= 1 + (9 + ( 16 + ( 4 + ( 25 +||||| 0)||| ) ) ) = 55
Thanks for help
+ 1
ZIZO Abd alkawy, do not look at my code, look at the result of its work âșïž
0
Solo your code is hard a bit to me to understand. But anyway thanks for help