Computer Science
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) ?
Python Functions
3 Likes
Answer
True is returned by check(8).
Explanation
The provided code defines a recursive function check(n)
that takes single argument. Inside the function, it checks if a given number n
is less than or equal to 1, in which case it returns True. If n
is even (i.e., divisible by 2 without a remainder), the function recursively calls itself with n/2. If n
is odd, it recursively calls itself with n/1 (which effectively does not change n
). However, the condition n/1
doesn't modify n
and leads to an infinite recursion for odd numbers greater than 1, causing the function to keep calling itself indefinitely without reaching a base case.
Answered By
3 Likes
Related Questions
Predict the output of the following code.
def code (n) : if n==0: print ( 'Finally' ) else: print (n) print (n-3) code (10)
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)
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)
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)