0

How to create a terminating function?

21st Jun 2017, 6:27 PM
Rishab Patil
Rishab Patil - avatar
2 ответов
+ 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).
21st Jun 2017, 8:29 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
0
What is it terminating?
21st Jun 2017, 7:36 PM
Sapphire