0
can some one help me
What is the result of this code? def power(x, y): if y == 0: return 1 else: return x * power(x, y-1) print(power(2, 3))
6 Réponses
+ 5
first, start looking if x and y are defined (they are, its x=2 and y=3)
second, try if y = 0, which is false, so else is true
third, just do the math
x * (x^(y-1))
2 * (2^(3-1))
2 * (2^2)
2 * 4
8
so the output will be 8
+ 1
its 8
+ 1
All these explanations are incomplete.
This is a recursion.
First level: 2 * power(2, 3-1),
Second level: 2 * (2* power(2, 2-1)),
Third level: 2 * (2 * (2 * power(2, 1-1))),
and because 1-1=0 and 0 returns a 1
So finally: 2 * (2 * (2 * 1)) which is equals to 8.
- 1
Here is my answer:
The first condition (if y == 0, return 1) isn't true because y is 3 and 3 is not equal to 0. Hence, the second condition needs to be checked and following the condition (return x * power(x, y-1) x is 2 while y is 3. Therefore, 2 * power (2, 3-1). So this turns out to be 2 * power(2,2). Then, following the operator precedence method, the operands in the curly braces needs to be calculated, which becomes 4. Hence, 2 * power (4). Finally, 2 multiplied 4 will give us 8.
To me this is my answer to the problem
- 1
What is the result of this code?
def power(x, y):
if y == 0:
return 1
else:
return x * power(x, y-1)
print(power(2, 3))
Ans:8
Explanation:
The first condition is not True (if y == 0, return 1) .because y is 3 and 3 is not equal to 0.
Hence, the second condition needs to be checked and following the condition (return x * power(x, y-1) x is 2 while y is 3. Therefore, 2 * power (2, 3-1). So this turns out to be 2 * power(2,2).
Then following the operator precedence method, the operands in the curly braces needs to be calculated, which becomes 4.
Hence, 2 * power (4). Finally, 2 multiplied 4 will give us 8.
- 1
Ans 8