0
self reference function?
Decided to try the challenges section and this code came up. The correct answer is 300 but I'm not sure how this works, it's definitely not 102 like I thought it was. def f(n): if n == 0: return 0 else: return f(n-1)+100 print(f(3)) Anyone able to clear this up for me?
2 Antworten
+ 1
@sayan of course! Thank you for your explanation
0
f(3) = f(2) + 300= f(1)+ 100+ 100 =f(0) + 100 + 100 + 100= 0+ 100+ 100 + 100= 300
check it out
the code runs upto n=0
and for f(0) the return value is 0
so the code ran 4 times
for 3 then for 2 then for 1 then for 0
so( 100+100+100+0) = 300