0
How to create a terminating function?
2 Respuestas
+ 4
If you are speaking about the base case, needed for every recursive function not to end up as infinite loop, you have to specify it as a condition of argument.
For example:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(6))
>>>
720
The base case, in this example if n is 0 or 1, is making the recursion to take a fixed value and rollback all the higher level calculations based on it.
Otherwise, it would be infinitely looking for itself's value of n-1 up to minus infinity (or out of memory, to be precise).
0
What is it terminating?