Computer Science
Can you find an error or problem with the below code? Think about what happens if we evaluate check(3). What output would be produced by Python? Explain the reason(s) behind the output.
def check (n) :
if n <=1:
return True
elif n % 2 == 0:
return check (n/2)
else:
return check (n/1)
Python Functions
1 Like
Answer
Yes, there is a error in the provided code. If we evaluate check(3)
, it will result in an infinite recursion and eventually lead to an error.
This happens because when check(3)
is called, the function first checks if n
is less than or equal to 1, which is not the case. Since n
is odd (i.e., n % 2 == 1), it enters the else
block and calls check(n/1)
which leads to the same value of n
being passed recursively to the function without any change. As a result, the function keeps calling itself with the same value of n
, leading to an infinite loop of recursion.
Answered By
1 Like
Related Questions
Predict the output of the following code:
def express (x, n) : if n == 0: return 1 elif n % 2 == 0: return express (x*x, n/2) else: return x * express (x, n-1) express (2, 5)
Consider the following Python function that uses recursion.
def check (n) : if n <=1: return True elif n % 2 == 0: return check (n/2) else: return check (n/1)
What is the value returned by check(8) ?
Consider the following Python function Fn(), that follows:
def Fn(n): print (n, end=" ") if n < 3: return n else: return Fn (n//2) - Fn (n//3)
What will be the result produced by the following function calls?
- Fn (12)
- Fn (10)
- Fn (7)
Figure out the problem with the following code that may occur when it is run.
def recur(p): if p == 0: print ("##") else: recur(p) p = p - 1