Computer Science
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
Python Functions
1 Like
Answer
The error in the provided code is that inside the else
block the value of p
is modified after the recursive call. This leads to an infinite recursion because p remains the same in each recursive call, never reaching the base case (p == 0) and causing the program to enter an infinite loop.
Explanation
The corrected code is:
def recur(p):
if p == 0:
print("##")
else:
recur(p - 1)
In this corrected version, p
is decremented by 1 in each recursive call, ensuring that the recursive process eventually reaches the base case where p == 0 and terminates the recursion.
Answered By
2 Likes
Related Questions
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)
Write a method in Python to find and display the prime numbers from 2 to N. The value of N should be passed as an argument to the method.
Write a method EvenSum(NUMBERS) to add those values in the tuple of NUMBERS which are even.