what is the output of following python code without running the code on python compiler? def test( i, j ): if(j==1): return i else: return test( i+1, j-1 )print(test( 4, 6 ))
Question
what is the output of following python code without running the code on python compiler? def test( i, j ): if(j==1): return i else: return test( i+1, j-1 )print(test( 4, 6 ))
Solution
The function test is a recursive function. Here's how it works:
- The function
testtakes two arguments,iandj. - If
jis equal to 1, it returnsi. - If
jis not equal to 1, it calls itself withi+1andj-1.
Let's break down the call test(4, 6):
jis not 1, so it callstest(5, 5).- Again,
jis not 1, so it callstest(6, 4). - Again,
jis not 1, so it callstest(7, 3). - Again,
jis not 1, so it callstest(8, 2). - Again,
jis not 1, so it callstest(9, 1). - Now,
jis 1, so it returnsi, which is 9.
So, the output of the code will be 9.
Similar Questions
swerWhat will be the output of the following Python code?def demo(p,q): if(p == 0): return q else: return demo(p-1,p+q)print(demo(4,5))
What will be the output of the following Python code?1. def foo():2. try:3. print(1)4. finally:5. print(2)6. 7. foo()
What will be printed by the following code?for i in range(5): for j in range(5, 0, -1): if i == j: print(i, end=" ")
What will be the output of the following Python code?def foo(k): k = [1]q = [0]foo(q)print(q)
What will be the output of the following program in Python?print(0 or 1)
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.