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))

3rd Jul 2018, 3:37 PM
jazzmine susana gomez coc
jazzmine susana gomez coc - avatar
6 Antworten
+ 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
3rd Jul 2018, 3:43 PM
Roel
Roel - avatar
+ 1
its 8
20th Nov 2019, 4:17 PM
Roberto Salazar-Abrego Jr.
Roberto Salazar-Abrego Jr. - avatar
+ 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.
27th Sep 2022, 9:17 AM
Eugene Teh
Eugene Teh - avatar
- 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
3rd Nov 2019, 7:48 PM
Abraham Emmanuel
Abraham Emmanuel - avatar
- 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.
6th Dec 2020, 6:48 AM
IRFAN KHAN
IRFAN KHAN - avatar
- 1
Ans 8
3rd Dec 2021, 2:32 PM
Thuwayba Ahmed
Thuwayba Ahmed - avatar