0
Example of Recursion
2 odpowiedzi
+ 2
The most basic example of recursion is the facorial function:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
You can see the base case, where n == 1 is checked, without this one it would be an infinite loop. The base case is a necessary case in recursion.
The other necessary thing in recursion is the fact that for some cases, the function calls itself, in order to loop.
+ 2
Though not a Python example, contrast can really help. This shows a very simple recursive factorial against the more complex iterative version.
https://chortle.ccsu.edu/java5/Notes/chap72/ch72_8.html