+ 1
who can explain this
the answer is seven '1' ... def f(x): if x==0 or x==1: return 1 else: print(f(x-1)) return f(x-1) #print(f(4)) f(4)
2 Answers
+ 2
Here are a few points to explain a lot of it. Consider each point until you're confident why it is correct before moving on.
The #print(f(4)) does nothing because it is a comment but you probably knew that.
The function's return value is always 1 because that's what the base case returns and the general case doesn't make any change to the returned value. "general case" = the else section or "x != 0 and x != 1". "base case" = the "x==0 or x==1" case.
In every case except the base case, the function makes 2 recursive calls. This means if f gets called with a value of 4, 2^(something related to 4) more calls will be made to f.
Here is a little ASCII art to illustrate the recursive branching structure this leads to where the number corresponds with each call's value of x:
_4_
/ \
3 3
/ \ / \
2 2 2 2
/ \ / \ / \ / \
1 1 1 1 1 1 1 1
Count the number of values greater than 1 and you get 7 just like you found. That makes sense when each call with a value greater than 1 directly prints 1 one time.
How would you describe what the function does?
Given a value x, the f prints "1" ( 2 ^ (x - 1) ) - 1 times where ^ indicates exponent.
0
Without the print statements you would have 4 function calls.
Each function which calls the function goes into a stack.
f(4) -> f(3) -> f(2) -> f(1) -> return 1
The stack:
f(2)
f(3)
f(4)
f(2) gets 1 from f(1).
f(3) gets 1 from f(2).
f(4) gets 1 from f(3).
Stack is empty. f(4) returns 1.
With the print statements you have 15 function calls. Each f(x) with x > 1 prints 1.
If you add print(x) at the beginning the function you will see all function calls.
If you change the print statement to print(x, f(x - 1)) you will see which function prints 1:
f(2) prints 1
f(3) prints 1
f(2) prints 1
f(4) prints 1
f(2) prints 1
f(3) prints 1
f(2) prints 1
The order has to do with the stack. But with the recursion tree from Josh Greig you should be able to understand it.